ServiceStack REST服务中的自定义异常处理

Ale*_* G. 6 c# api rest custom-errors servicestack

我有一个ServiceStack REST服务,我需要实现自定义错误处理.我已经能够通过将AppHostBase.ServiceExceptionHandler设置为自定义函数来自定义服务错误.

但是,对于其他类型的错误,例如验证错误,这不起作用.我怎样才能涵盖所有案件?

换句话说,我正在努力实现两件事:

  1. 为可能弹出的每种异常设置我自己的HTTP状态代码,包括非服务错误(验证)
  2. 为每种错误类型返回我自己的自定义错误对象(不是默认的ResponseStatus)

我将如何实现这一目标?

myt*_*thz 11

AppHostBase.ServiceExceptionHandler全球处理器只能处理服务异常.要处理服务之外发生的异常,您可以设置全局AppHostBase.ExceptionHandler处理程序,例如:

public override void Configure(Container container)
{
    //Handle Exceptions occurring in Services:
    this.ServiceExceptionHandler = (request, exception) => {

        //log your exceptions here
        ...

        //call default exception handler or prepare your own custom response
        return DtoUtils.HandleException(this, request, exception);
    };

    //Handle Unhandled Exceptions occurring outside of Services, 
    //E.g. in Request binding or filters:
    this.ExceptionHandler = (req, res, operationName, ex) => {
         res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
         res.EndServiceStackRequest(skipHeaders: true);
    };
}
Run Code Online (Sandbox Code Playgroud)

要在非服务中 创建DCD并将其序列化到响应流,ExceptionHandler您需要访问并使用正确的序列化程序来处理来自IAppHost.ContentTypeFilters的请求.

有关更多详细信息,请参阅错误处理Wiki页面.