Search code examples
c#servicestackservicestack-bsd

Do I have access to the request dto when I'm handling exceptions occuring outside of services?


With ServiceStack, it's important to implement exception handling/logging in two places:

  1. Inside of each ServiceRunner<T>.

       public class MyServiceRunner<T> : ServiceRunner<T>
       {    
            public override object HandleException(IRequestContext requestContext, T request, Exception ex)
              {
                    // Implement your exception handling/logging here.
                    // T request is your request DTO.
              }
        }
    
  2. Inside of AppHost, so that you can handle unhandled exceptions occuring outside of services.

    public override void Configure(Container container)
    {
        ExceptionHandler = (req, res, operationName, ex) =>
        {
            //Handle Unhandled Exceptions occurring outside of Services
            //E.g. Exceptions during Request binding or in filters:
        }
     }
    

My Question:

  • In #1, you have easy access to the request DTO (i.e. for logging purposes).
  • Do I have access to the request DTO (or the request payload equivalent) when I'm handling exceptions occuring outside of services?

Solution

  • In ServiceStack v4 the Request DTO is available from IRequest.Dto, but you would instead register your Service and Unknown Exception handlers with IAppHost.ServiceExceptionHandlers and IAppHost.UncaughtExceptionHandlers

    In ServiceStack V3, you could register a GlobalRequestFilter that stores the Request DTO in IRequestContext.Items dictionary which you can get later from the Request Context.