Marco Serina
Marco Serina

Reputation: 11

ServiceStack Custom ErrorResponse DTO

We are currently using ServiceStack as our core framework for service provisioning. Does anyone know if it's possible to wrap custom exceptions into custom ErrorResponse objects?

From SS wiki:

"In addition to the above options, you can override the serialization of ad-hoc exceptions by implementing the IResponseStatusConvertible.ToResponseStatus() method and have it return your own populated ResponseStatus instance instead."

That seems to fit with my needs, but I cannot figure out where I can override this serialization.

Again, I've tried to use custom httphandler by registering them within the AppHost, but they are not invoked when exceptions occur.

I am certainly missing something, is there anyone who can guide me through this?

Upvotes: 1

Views: 668

Answers (1)

mythz
mythz

Reputation: 143319

Here is ServiceStack's Error Handling wiki page.

What it's saying is that you can control how the ResponseStatus is serialized if your custom exceptions implement IResponseStatusConvertible. Here is the source code example of ValidationException implementing it:

public class ValidationException : ArgumentException, IResponseStatusConvertible 
{
    public IEnumerable<ValidationFailure> Errors { get; private set; }

    public ValidationException(IEnumerable<ValidationFailure> errors) : base(BuildErrorMesage(errors)) {
        Errors = errors;
    }

    private static string BuildErrorMesage(IEnumerable<ValidationFailure> errors) {
        var arr = errors.Select(x => "\r\n -- " + x.ErrorMessage).ToArray();
        return "Validation failed: " + string.Join("", arr);
    }

    public ResponseStatus ToResponseStatus()
    {
        var errors = Errors.ConvertAll(x =>
            new ValidationErrorField(x.ErrorCode, x.PropertyName, x.ErrorMessage));

        var responseStatus = ResponseStatusUtils.CreateResponseStatus(typeof(ValidationException).Name, Message, errors);
        return responseStatus;
    }
}

But this only controls how ResponseStatus is serialized, not how the generic responses are created. Look at the description of IAppHost.ServiceExceptionHandler or use a custom service runner if you want to change the error response returned.

Upvotes: 1

Related Questions