【问题标题】:Catching exceptions with servicestack使用 servicestack 捕获异常
【发布时间】:2012-10-20 01:24:28
【问题描述】:

我们已经将 ServiceStack 用于基于 REST 的服务已经有一段时间了,到目前为止它已经很棒了。

我们所有的服务都写成:

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

对于每个 DTO,我们都有 Response 等效对象:

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

它会处理所有被抛出的异常。

我注意到,如果在 OnGet()OnPost() 方法中抛出异常,那么 http 状态描述包含异常类的名称,就好像我抛出了一个:

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

那么http状态描述包含文本“Some Message”。

由于一些 REST 服务正在抛出异常,而另一些正在抛出 new HttpError(),我想知道是否有一种方法可以在不更改所有 REST 服务的情况下捕获任何异常并抛出 new HttpError()?

例如,如果OnGet() 方法抛出异常,那么捕获它并抛出new HttpError()

【问题讨论】:

    标签: servicestack


    【解决方案1】:

    使用旧 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's improved 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
        }
    }
    

    【讨论】:

    • 感谢您的帮助。但是,如何返回 Response 对象?目前,如果我抛出错误,则不返回响应对象(序列化),响应对象不存在。
    • 我做了以下事情:protected override object HandleException(TRequest request, Exception ex) { _logger.error(ex.message); return base.HandleException(request, ex); }
    猜你喜欢
    • 2017-07-14
    • 2013-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多