Custom Exception Handling in ServiceStack REST

I have a ServiceStack REST service and I need to implement custom error handling. I was able to configure service errors by setting AppHostBase.ServiceExceptionHandler in a user-defined function.

However, for other types of errors, such as validation errors, this does not work. How can I cover all cases?

In other words, I am trying to achieve two things:

  • Set my own HTTP status codes for all kinds of exceptions that may occur, including non-maintenance errors (check)
  • Return own error object of its own (not default ResponseStatus) for each type of error

How can I achieve this?

+6
source share
2 answers

The global handler AppHostBase.ServiceExceptionHandler handles only service exceptions . To handle exceptions that occur outside of services, you can set the global handler AppHostBase.ExceptionHandler , for example:

 public override void Configure(Container container) { //Handle Exceptions occurring in Services: this.ServiceExceptionHandler = (request, exception) => { //log your exceptions here ... //call default exception handler or prepare your own custom response return DtoUtils.HandleException(this, request, exception); }; //Handle Unhandled Exceptions occurring outside of Services, //Eg in Request binding or filters: this.ExceptionHandler = (req, res, operationName, ex) => { res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message)); res.EndServiceStackRequest(skipHeaders: true); }; } 

To create and serialize a DTO for a response flow in a non- ExceptionHandler service , you need to access and use the correct serializer for the request from IAppHost.ContentTypeFilters .

See the wiki page for error handling for more information.

+11
source

I improved @mythz 's answer.

 public override void Configure(Container container) { //Handle Exceptions occurring in Services: this.ServiceExceptionHandlers.Add((httpReq, request, exception) = > { //log your exceptions here ... //call default exception handler or prepare your own custom response return DtoUtils.CreateErrorResponse(request, exception); }); //Handle Unhandled Exceptions occurring outside of Services //Eg Exceptions during Request binding or in filters: this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) = > { res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message)); #if !DEBUG var message = "An unexpected error occurred."; // Because we don't want to expose our internal information to the outside world. #else var message = ex.Message; #endif res.WriteErrorToResponse(req, req.ContentType, operationName, message, ex, ex.ToStatusCode()); // Because we don't want to return a 200 status code on an unhandled exception. }); } 
+4
source

All Articles