在ServiceStack REST服务自定义异常处理 [英] Custom exception handling in ServiceStack REST service

查看:616
本文介绍了在ServiceStack REST服务自定义异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a ServiceStack REST service and I need to implement custom error handling. I've been able to customize service errors by setting AppHostBase.ServiceExceptionHandler to a custom function.

然而,对于其他类型的错误,诸如验证错误,这是行不通的。我怎么能覆盖所有的情况?

However, for other types of errors, such as validation errors, this doesn't work. How can I cover all cases?

在换句话说,我试图做到两件事:

In other words, I'm trying to achieve two things:


  1. 设置自己的HTTP状态codeS为每一种异常,可能弹出,包括非服务错误(验证)

  2. 返回自己的自定义错误对象(不是默认ResponseStatus)为每个错误类型

我将如何去实现呢?

推荐答案

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

The AppHostBase.ServiceExceptionHandler global handler only handles service exceptions. To handle exceptions occurring outside of services you can set the global AppHostBase.ExceptionHandler handler, e.g:

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);
    };
}

要创建并在非职务序列化DTO响应流 的ExceptionHandler 您需要的access并使用正确的串行从IAppHost.ContentTypeFilters 的请求。

To create and serialize a DTO to the response stream in the non-service ExceptionHandler you would need to access and use the correct serializer for the request from IAppHost.ContentTypeFilters.

更多细节是在错误处理维基页面

这篇关于在ServiceStack REST服务自定义异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆