识别Servicestack的ExceptionHandler中的异常类型

时间:2017-06-14 11:55:28

标签: c# servicestack-bsd

servicestack中的ExceptionHandler(在被覆盖的AppHostBase的Configure方法中设置)具有'异常' lambda中泛型异常类型的参数。

this.ExceptionHandler = (httpReq, httpResp, operationName, exception) =>
{
    if(exception is ArgumentException)
    {
      // some code
    }
}

在lambda中,如果异常是ArgumentException类型,我希望添加一个特定的条件。 有没有办法确定抛出哪种特定类型的异常? 用'检查类型是'关键字无效,因为此link

仅供参考,我们使用的servicestack实例实现了自定义ServiceRunner。

1 个答案:

答案 0 :(得分:0)

导致ArgumentException的代码是

return serializer.Deserialize(querystring, TEMP);

由于某种原因,在ArgumentException

中无法将异常对象识别为ExceptionHandler
this.ExceptionHandler = (httpReq, httpResp, operationName, exception) =>
{
    httpResp.StatusCode = 500;
    bool isArgEx = exception is ArgumentException; // returns false        
    if(isArgEx)
    {
        //do something
    }
}

虽然如链接中所述(请参阅问题),但可以使用is关键字识别 InnerException

因此,应用的解决方案是将ArgumentException作为内部异常抛出,如下所示:

public const string ARG_EX_MSG = "Deserialize|ArgumentException";

try
{
    return serializer.Deserialize(querystring, TEMP);
}
catch(ArgumentException argEx)
{
    throw new Exception(ARG_EX_MSG, argEx);
}

因此,现在ExceptionHandler代码是:

this.ExceptionHandler = (httpReq, httpResp, operationName, exception) =>
{
    httpResp.StatusCode = 500;
    bool isArgEx = exception.InnerException is ArgumentException; // returns true
    if(isArgEx)
    {
        //do something
    }
}
相关问题