当前位置: 移动技术网 > IT编程>开发语言>.net > ServiceStack 错误处理

ServiceStack 错误处理

2019年03月13日  | 移动技术网IT编程  | 我要评论

台湾同婚平权运动31年,海贼动漫网,幻梦之晓1.41攻略

抛出c#异常

在大多数情况下,您不需要关心servicestack的错误处理,因为它为抛出c#异常的正常用例提供本机支持,例如:

public object post(user request) 
{
    if (string.isnullorempty(request.name))
        throw new argumentnullexception("name");
}

http错误c#异常的默认映射

默认c#例外:

  • argumentexception使用http statuscode为400 badrequest返回继承
  • notimplementedexception或者notsupportedexception 作为405 methodnotallowed返回
  • authenticationexception401 unauthorized身份返回
  • unauthorizedaccessexception403 forbidden返回
  • optimisticconcurrencyexception返回409冲突
  • 其他正常的c#异常作为500 internalservererror返回

可以使用用户定义的映射扩展此列表config.mapexceptiontostatuscode

webserviceexception

所有异常都被注入到responsestatus响应dto 属性中,属性被序列化到serviceclient的首选内容类型中,使得错误处理变得透明,无论您的首选格式如何 - 即,相同的c#错误处理代码可用于所有serviceclient。

try 
{
    var client = new jsonserviceclient(baseuri);
    var response = client.send<userresponse>(new user());
} 
catch (webserviceexception webex) 
{
    /*
      webex.statuscode        = 400
      webex.statusdescription = argumentnullexception
      webex.errorcode         = argumentnullexception
      webex.errormessage      = value cannot be null. parameter name: name
      webex.stacktrace        = (your server exception stacktrace - in debugmode)
      webex.responsedto       = (your populated response dto)
      webex.responsestatus    = (your populated response status dto)
      webex.getfielderrors()  = (individual errors for each field if any)
    */
}

 

其中statuscodestatusdescription是http statuscode和description,显示所有http客户端看到的顶级http层详细信息。statusdescription通常很短,用于指示返回的错误类型,默认情况下是抛出的异常类型。http客户端通常会检查statuscode以确定如何在客户端上处理错误。

所有还可以访问错误响应dto主体中返回的应用程序级错误详细信息,其中errorcode包含异常类型,客户端将检查以确定和处理异常类型,同时errormessage保存服务器异常消息它提供了一个人性化的,更长和描述性的错误描述,可以显示给最终用户。stacktrace使用server stacktrace填充,以帮助前端开发人员识别错误的原因和位置。

如果错误引用特定字段(如字段验证异常),则getfielderrors()保留每个具有错误的字段的错误信息。

可以通过以下各种选项更改这些默认值以提供进一步的自定义错误响应:

启用s​​tacktraces

默认情况下,在响应dto中显示stacktraces仅在调试版本中启用,尽管此行为可以通过以下方式覆盖:

setconfig(new hostconfig { debugmode = true });

错误响应类型

抛出异常时返回的错误响应取决于是否存在常规命名的{requestdto}responsedto。

如果存在:

{requestdto}response返回,而不管服务方法的响应类型的。如果{requestdto}responsedto具有responsestatus属性,则会填充它,否则将不返回responsestatus(如果{responsedto}response使用[datacontract]/[datamember]属性修饰了类和属性,则还需要对responsestatus进行修饰以填充)。

否则:

通过errorresponse填充的responsestatus属性返回泛型

透明地处理不同的错误响应类型,并为无模式格式,如json / jsv /等有返回之间没有实际明显的区别responsestatus自定义或通用的errorresponse-因为它们都输出电线上的同样的反应。

自定义例外

最终,所有servicestack webserviceexceptions都只是response dto,其中包含一个填充的responsestatus,它返回http错误状态。有多种不同的方法可以自定义异常的返回方式,包括:

自定义c#异常到http错误状态的映射

您可以通过以下方式配置为不同的异常类型更改返回的http错误状态:

 

setconfig(new hostconfig { 
    mapexceptiontostatuscode = {
        { typeof(custominvalidroleexception), 403 },
        { typeof(customernotfoundexception), 404 },
    }
});

 

返回httperror

如果你想要对你的http错误进行更细粒度的控制,你可以抛出返回一个httperror,让你自定义http headersstatus code和http response body以便在线上获得你想要的内容:

public object get(user request) 
{
    throw httperror.notfound("user {0} does not exist".fmt(request.name));
}

 

以上内容在线路上返回404 notfound statuscode,是以下方面的简写:

new httperror(httpstatuscode.notfound, 
    "user {0} does not exist".fmt(request.name)); 

 

具有自定义响应dto的httperror

httperror还可用于返回更结构化的错误响应:

var responsedto = new errorresponse { 
    responsestatus = new responsestatus {
        errorcode = typeof(argumentexception).name,
        message = "invalid request",
        errors = new list<responseerror> {
            new responseerror {
                errorcode = "notempty",
                fieldname = "company",
                message = "'company' should not be empty."
            }
        }
    }
};

throw new httperror(httpstatuscode.badrequest, "argumentexception") {
    response = responsedto,
}; 

 

实现iresponsestatusconvertible

您还可以通过实现iresponsestatusconvertible接口来覆盖自定义异常的序列化,以返回您自己填充的responsestatus。这是validationexception允许通过让validationexception实现iresponsestatusconvertible接口来自定义response dto 方法

例如,这是一个自定义的exception示例,它返回填充的字段错误:

public class customfieldexception : exception, iresponsestatusconvertible
{
  ...
    public string fielderrorcode { get; set; }
    public string fieldname { get; set; }
    public string fieldmessage { get; set; }

    public responsestatus toresponsestatus()
    {
        return new responsestatus {
            errorcode = gettype().name,
            message = message,
            errors = new list<responseerror> {
                new responseerror {
                    errorcode = fielderrorcode,
                    fieldname = fieldname,
                    message = fieldmessage
                }
            }
        }
    }    
}

 

实现ihasstatuscode

除了使用自定义c#exceptions的http response body,您还可以通过实现ihasstatuscode以下内容来自定义http状态代码

public class custom401exception : exception, ihasstatuscode
{
    public int statuscode 
    { 
        get { return 401; } 
    }
}

 

同样ihasstatusdescription可以用于自定义statusdescriptionihaserrorcode自定义errorcode返回的,而不是其异常类型。

覆盖apphost中的onexceptiontypefilter

您还可以responsestatus通过覆盖onexceptiontypefilterapphost 来捕获和修改返回的返回值,例如servicestack使用它来自定义返回的responsestatus以自动为argumentexceptions指定的字段添加自定义字段错误paramname,例如:

public virtual void onexceptiontypefilter(
    exception ex, responsestatus responsestatus)
{
    var argex = ex as argumentexception;
    var isvalidationsummaryex = argex is validationexception;
    if (argex != null && !isvalidationsummaryex && argex.paramname != null)
    {
        var parammsgindex = argex.message.lastindexof("parameter name:");
        var errormsg = parammsgindex > 0
            ? argex.message.substring(0, parammsgindex)
            : argex.message;

        responsestatus.errors.add(new responseerror
        {
            errorcode = ex.gettype().name,
            fieldname = argex.paramname,
            message = errormsg,
        });
    }
}

 

自定义http错误

在任何请求或响应过滤器中,您可以通过发出自定义http响应并结束请求来短路,例如:

this.prerequestfilters.add((req,res) => 
{
    if (req.pathinfo.startswith("/admin") && 
        !req.getsession().hasrole("admin")) 
    {
        res.statuscode = (int)httpstatuscode.forbidden;
        res.statusdescription = "requires admin role";
        res.endrequest();
    }
});

 

在自定义httphandler中结束请求使用 res.endhttphandlerrequest()

后备错误页面

使用iapphost.globalhtmlerrorhttphandler用于指定后备httphandler的所有错误状态代码,例如:

public override void configure(container container)
{
    this.globalhtmlerrorhttphandler = new razorhandler("/oops"),
}

 

要获得更细粒度的控制,请使用iapphost.customerrorhttphandlers指定自定义httphandler以与特定错误状态代码一起使用,例如:

public override void configure(container container)
{
    this.customerrorhttphandlers[httpstatuscode.notfound] = 
        new razorhandler("/notfound");
    this.customerrorhttphandlers[httpstatuscode.unauthorized] = 
        new razorhandler("/login");
}

 

注册处理服务异常的处理程序

servicestack及其提供了一种拦截异常的灵活方法。如果你需要的所有服务异常的单一入口点,您可以将处理程序添加到apphost.serviceexceptionhandlerconfigure要处理服务之外发生的异常,您可以设置全局apphost.uncaughtexceptionhandlers处理程序,例如:

public override void configure(container container)
{
    //handle exceptions occurring in services:

    this.serviceexceptionhandlers.add((httpreq, request, exception) => {
        //log your exceptions here
        ...
        return null; //continue with default error handling

        //or return 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: {ex.gettype().name}: {ex.message}");
         res.endrequest(skipheaders: true);
    });
}

 

异步异常处理程序

如果您的处理程序需要进行任何异步调用,则可以使用async版本:

this.serviceexceptionhandlersasync.add(async (httpreq, request, ex) =>
{
    await logserviceexceptionasync(httpreq, request, ex);

    if (ex is unhandledexception)
        throw ex;

    if (request is iquerydb)
        return dtoutils.createerrorresponse(request, new argumentexception("autoquery request failed"));

    return null;
});

this.uncaughtexceptionhandlersasync.add(async (req, res, operationname, ex) =>
{
    await res.writeasync($"uncaughtexception '{ex.gettype().name}' at '{req.pathinfo}'");
    res.endrequest(skipheaders: true);
});

 

使用自定义servicerunner进行错误处理

如果您想为不同的操作和服务提供不同的错误处理程序,您可以告诉servicestack在您自己的自定义iservicerunner中运行您的服务,在apphost中实现handleexcepion事件挂钩:

public override iservicerunner<trequest> createservicerunner<trequest>(
    actioncontext actioncontext)
{           
    return new myservicerunner<trequest>(this, actioncontext); 
}

 

其中myservicerunner就是实现你感兴趣的,如自定义挂钩的自定义类:

public class myservicerunner<t> : servicerunner<t> 
{
    public myservicerunner(iapphost apphost, actioncontext actioncontext) 
        : base(apphost, actioncontext) {}

    public override object handleexception(irequest request, 
        t request, exception ex) {
      // called whenever an exception is thrown in your services action
    }
}

 

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网