Catching exceptions with servicestack

天涯浪子 提交于 2019-11-30 14:38:48

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
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!