2017-06-14 23 views
0

servicestack的ExceptionHandler(在AppHostBase的重寫的Configure方法內設置)在lambda表中具有泛型Exception類型的'exception'參數。在ServiceStack的ExceptionHandler中標識異常的類型

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

在lambda裏面,我希望添加一個特定的條件,如果例外是ArgumentException類型。 有什麼方法可以確定拋出哪種特定類型的異常? 使用「is」關鍵字檢查類型是不行的link

僅供參考,爲我們使用的servicestack實例實現了自定義的ServiceRunner。

+0

據我明白在答案它正在工作的鏈接問題!? –

+0

是的,它是。如果你的代碼塊沒有運行,那麼異常的類型不是ArguementException。嘗試調試代碼以查看它是什麼類型的異常,或嘗試'exception.GetType()。ToString()'。 – Scrobi

+0

ServiceStack v4中沒有'ExceptionHandler',如果是[ServiceStack v3,您需要使用\ [servicestack-bsd \]哈希標記](https://github.com/servicestackv3/servicestackv3#support)。 – mythz

回答

0

導致該ArgumentException

return serializer.Deserialize(querystring, TEMP); 

出於某種原因,該代碼段,所述異常對象不能被識別爲ExceptionHandler

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

雖然內部的ArgumentException,如在鏈接中提到(請參考問題)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 
    } 
} 
相關問題