【问题标题】:Identify type of exception in ExceptionHandler of Servicestack识别Servicestack的ExceptionHandler中的异常类型
【发布时间】:2017-06-14 11:55:28
【问题描述】:

servicestack 的 ExceptionHandler(设置在 AppHostBase 的重写 Configure 方法中)在 lambda 中具有通用 Exception 类型的 'exception' 参数。

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

在 lambda 内部,如果异常是 ArgumentException 类型,我希望添加一个特定条件。 有什么方法可以确定引发了哪种特定类型的异常? 使用 'is' 关键字检查类型不起作用,正如 link 给出的那样

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

【问题讨论】:

  • 据我了解链接问题中的答案有效!?
  • 是的。如果您的代码块未运行,则异常类型不是 ArguementException。尝试调试代码以查看它是什么类型的异常或尝试exception.GetType().ToString()
  • ServiceStack v4 中没有ExceptionHandler,如果这是ServiceStack v3 you need to use the [servicestack-bsd] hash tag
  • 我再次检查了,但由于某种原因异常对象无法识别为ExceptionHandler内的ArgumentException。最后,下面回答的解决方案有效。

标签: c# servicestack-bsd


【解决方案1】:

导致ArgumentException 的代码是

return serializer.Deserialize(querystring, TEMP);

由于某种原因,异常对象无法识别为ExceptionHandler 内的ArgumentException

this.ExceptionHandler = (httpReq, httpResp, operationName, exception) =>
{
    httpResp.StatusCode = 500;
    bool isArgEx = exception is ArgumentException; // returns false        
    if(isArgEx)
    {
        //do something
    }
}

尽管如链接中所述(请参阅问题),InnerException 可以使用 is 关键字来识别。

因此应用的解决方案是将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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-16
    • 2015-06-19
    • 2016-08-10
    • 2017-03-29
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-11-11
    相关资源
    最近更新 更多