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

时间:2013-03-24 21:32:14

标签: c# api rest servicestack custom-errors

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

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

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

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

    我将如何实现这一目标?

2 个答案:

答案 0 :(得分: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);
    };
}

要在非服务 ExceptionHandler中创建DCD并将其序列化到响应流,您需要access and use the correct serializer for the request from IAppHost.ContentTypeFilters

有关详情,请参阅Error Handling wiki page

答案 1 :(得分:4)

我对@mythz' answer进行了改进。

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
    //E.g. 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.
    });
}