ServiceStack REST服务中的自定义exception处理

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

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

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

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

我将如何实现这一目标?

AppHostBase.ServiceExceptionHandler全局处理程序仅处理服务exception 。 要处理在服务之外发生的exception,您可以设置全局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, //Eg 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); }; } 

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

有关更多详细信息,请参阅error handlingWiki页面 。

我对@mythz的回答做了改进。

 public override void Configure(Container container) { //Handle Exceptions occurring in Services: this.ServiceExceptionHandlers.Add((httpReq, request, exception) = > { //log your exceptions here ... //call default exception handler or prepare your own custom response return DtoUtils.CreateErrorResponse(request, exception); }); //Handle Unhandled Exceptions occurring outside of Services //Eg Exceptions during Request binding or in filters: this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) = > { res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message)); #if !DEBUG var message = "An unexpected error occurred."; // Because we don't want to expose our internal information to the outside world. #else var message = ex.Message; #endif res.WriteErrorToResponse(req, req.ContentType, operationName, message, ex, ex.ToStatusCode()); // Because we don't want to return a 200 status code on an unhandled exception. }); }