5

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:

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

For each DTO we have Response equivalent object:

public class RestServiceDto 
{
    public ResponseStatus ResponseStatus {get;set;}
}

which handles all the exceptions should they get thrown.

What I noticed is if an exception is thrown in the OnGet() or OnPost() methods, then the http status description contains the name of the exception class where as if I threw a:

new HttpError(HttpStatus.NotFound, "Some Message");

then the http status description contains the text "Some Message".

Since some of the rest services are throwing exceptions and others are throwing new HttpError(), I was wondering if there was a way without changing all my REST services to catch any exceptions and throw a new HttpError()?

So for example, if the OnGet() method throws an exception, then catch it and throw a new HttpError()?

4

1 回答 1

9

使用旧 API - 继承自定义基类

当您使用旧 API 来处理异常时,您应该提供一个自定义基类并覆盖 HandleException 方法,例如:

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

然后利用自定义错误处理让您的所有服务都继承您的类,例如:

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

使用新 API - 使用 ServiceRunner

否则,如果您使用的是ServiceStack 改进的 New API,那么您不需要让所有服务都继承一个基类,而是可以通过覆盖 CreateServiceRunner 来告诉 ServiceStack 在您的 AppHost 中使用自定义运行器:

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

MyServiceRunner 只是一个实现您感兴趣的自定义钩子的自定义类,例如:

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
    }
}
于 2012-10-31T04:25:03.430 回答