Catching exceptions with servicestack

前端 未结 1 439
温柔的废话
温柔的废话 2021-01-03 01:30

We have been using ServiceStack for REST based services for a while now and so far it has been amazing.

All of our services have been written as:



        
相关标签:
1条回答
  • 2021-01-03 02:02

    Using Old API - inherit a custom base class

    As you're using the old API to handle exceptions generically you should provide a Custom Base class and override the HandleException method, e.g:

    public class MyRestServiceBase<TRequest> : RestService<TRequest>
    {
       public override object HandleException(TRequest request, Exception ex)
       {
           ...
           return new HttpError(..);
       }
    }
    

    Then to take advantage of the custom Error handling have all your services inherit your class instead, e.g:

    public class MyRestService : MyRestServiceBase<RestServiceDto>
    {
       public override object OnGet(RestServiceDto request)
       {    
       }
    }
    

    Using New API - use a ServiceRunner

    Otherwise if you're using ServiceStack's improved New API then you don't need to have all services inherit a base class, instead you can just tell ServiceStack to use a custom runner in your AppHost by overriding CreateServiceRunner:

    public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(
        ActionContext actionContext)
    {           
        return new MyServiceRunner<TRequest>(this, actionContext); 
    }
    

    Where MyServiceRunner is just a just custom class implementing the custom hooks you're interested in, e.g:

    public class MyServiceRunner<T> : ServiceRunner<T> {
        public override object HandleException(IRequestContext requestContext, 
            TRequest request, Exception ex) {
          // Called whenever an exception is thrown in your Services Action
        }
    }
    
    0 讨论(0)
提交回复
热议问题