Clone this wiki locally

Validation and Error Handling

As validation and error handling is an essential part of developing services, ServiceStack provides a rich array of error handling options that work intuitively out-of-the-box.

Optimized for developer happiness ServiceStack allows you to idiomatically throw C# exceptions directly in your services and trivially consume them on the client with minimal effort, intuitively and conventionally - allowing the opportunity to inject generic error handling routines to handle errors for all your web services.

For bonus REST Internet points the most appropriate HTTP Status code is returned based upon the C# Exception type.

Typed, Structured Exceptions end-to-end

The error handling support works end-to-end where all errors get auto-serialized into your Response DTO and re-hydrated into a C# Exception on ServiceStack's generic Service Clients. This allows you to idiomatically treat errors like normal C# Exceptions - providing easy access to rich, structured error messages in your clients.

JavaScript support included

To make it trivial to consume errors in JavaScript, you can use the lightweight ss-validation.js JavaScript library to trivially bind your response errors to your HTML form fields with a single line of code.

All Error handling and validation options described below are treated in the same way - serialized into the ResponseStatus property of your Response DTO making it possible for your clients applications to generically treat all Web Service Errors in the same way.

Note: The response DTO must follow the {Request DTO}Response naming convention and has to be in the same namespace as the request DTO!

Inheriting from ArgumentException are returned as a HTTP StatusCode of 400 BadRequest

NotImplementedException is returned as a 405 MethodNotAllowed

Other normal C# Exceptions are returned as 500 InternalServerError

All Exceptions gets injected into the ResponseStatus property of your Response DTO that is serialized into your ServiceClient's preferred Content-Type making error handling transparent regardless of your preferred format - i.e. the same C# Error handling code can be used for all ServiceClients.

Enabling StackTraces

By default display StackTraces in your Response DTOs are disabled, but they're a good to have for development, which you can enable with:

SetConfig(new EndpointHostConfig { DebugMode = true });

Customized Error Messages

If you want even finer grained control of your HTTP errors you can either throw or return a HttpError letting you customize the Http Headers and Status Code and HTTP Response body to get exactly what you want on the wire:

the above is a short-hand for new HttpError(HttpStatusCode.NotFound, string.Format("User {0} does not exist", request.Name)) which returns a 404 NotFound StatusCode on the wire.

Validation Feature

For more complex validation and to be able to return multiple validation errors ServiceStack includes the excellent Fluent Validation library by @JeremySkinner - a very clean and DSL-like way to validate request DTOs. Even contextual validation for each HTTP method (GET, POST, ...) is supported.

ServiceStack's Fluent Validation feature is encapsulated in the ValidationFeature plugin which can be registered in your AppHost with:

Info: ServiceStack adds another extension method named RuleSet which can handle ApplyTo enum flags. This method doesn't exist in the core FluentValidation framework.

Warning: If a validator for a request dto is created, all rules which aren't in any rule set are executed + the rules in the matching rule set.
Normally FluentValidation only executes the matching rule set and ignores all other rules (whether they're in a rule set or not) and the rules which don't belong
to any rule set are normally only executed, if no rule set-name was given to the validate method of the validator.

Like services registered in the IoC container, validators are also auto-wired, so if there's a public property which can be resolved by the IoC container, the IoC container will inject it. In this case, the IoC container will resolve the property AddressValidator, if an object of the type IAdressValidator was registered.

Tip: You can access the http request in a validator by implementing IRequiresHttpRequest. Attention, it's lazily loaded and so only available in the validation delegates.

Register Validatores

All validators have to be registered in the IoC container, a convenient way to register all validators which exist in one assembly is to use RegisterValidators(), e.g:

publicclassSomeService : Service
{
//You should have registered your validator in the IoC container to inject the validator into this propertypublic IValidator<TestClass> Validator { get; set; }
publicobjectGet(Validatedrequest)
{
TestClass instance = new TestClass();
ValidationResult result = this.Validator.Validate(instance);
if (!result.IsValid)
{
//The result will be serialized into a ValidationErrorException and throw this one//The errors will be serialized in a clean, human-readable way (as the above JSON example)throw result.ToException();
}
}
}

Populating the Response DTO Manually

All the error handling methods illustrated above are just sugar coating for serializing exceptions into your Response DTOs ResponseStatus property. You don't have use any of this as you can simply populate the ResponseStatus property yourself, coupled with the HttpResult class you have complete control of your HTTP Response - this gives you the necessary freedom so you are able to define your own Error handling API and helpers if you have an existing validation library that you would like to use instead.