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

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

问题描述

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

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

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

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

我将如何实现这一目标?

解决方案

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

public override void Configure(Container container){//处理服务中发生的异常:this.ServiceExceptionHandler = (请求,异常) =>{//在这里记录你的异常...//调用默认异常处理程序或准备您自己的自定义响应return DtoUtils.HandleException(this, request, exception);};//处理发生在服务之外的未处理异常,//例如.在请求绑定或过滤器中:this.ExceptionHandler = (req, res, operationName, ex) =>{res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));res.EndServiceStackRequest(skipHeaders: true);};}

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

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

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. Set my own HTTP status codes for every kind of exception that might pop up, including non-service errors (validation)
  2. Return my own custom error object (not the default ResponseStatus) for every error type

How would I go about achieving this?

解决方案

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

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.

More details about is in the Error Handling wiki page.

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

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