我们已经使用ServiceStack基于REST的服务已经有一段时间了,到目前为止它一直很棒.
我们所有的服务都写成:
public class MyRestService : RestService<RestServiceDto>
{
public override object OnGet(RestServiceDto request)
{
}
}
Run Code Online (Sandbox Code Playgroud)
对于每个DTO,我们都有Response等效对象:
public class RestServiceDto
{
public ResponseStatus ResponseStatus {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
如果它们被抛出,它会处理所有异常.
我注意到的是,如果在OnGet()或OnPost()方法中抛出异常,则http状态描述包含异常类的名称,就好像我扔了一样:
new HttpError(HttpStatus.NotFound, "Some Message");
Run Code Online (Sandbox Code Playgroud)
那么http状态描述包含文本"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()?
当您使用旧API来处理异常时,您应该提供Custom Base类并覆盖HandleException方法,例如:
public class MyRestServiceBase<TRequest> : RestService<TRequest>
{
public override object HandleException(TRequest request, Exception ex)
{
...
return new HttpError(..);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,为了利用自定义错误处理,您的所有服务都会继承您的类,例如:
public class MyRestService : MyRestServiceBase<RestServiceDto>
{
public override object OnGet(RestServiceDto request)
{
}
}
Run Code Online (Sandbox Code Playgroud)
否则,如果您正在使用ServiceStack改进的New API,那么您不需要让所有服务都继承基类,而是可以通过覆盖CreateServiceRunner告诉ServiceStack在AppHost中使用自定义运行器:
public override IServiceRunner<TRequest> CreateServiceRunner<TRequest>(
ActionContext actionContext)
{
return new MyServiceRunner<TRequest>(this, actionContext);
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1673 次 |
| 最近记录: |