ronilk
ronilk

Reputation: 372

Identify type of exception in ExceptionHandler of Servicestack

The ExceptionHandler(set inside the overridden Configure method of AppHostBase) of servicestack has the 'exception' parameter of generic Exception type in the lambda.

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

Inside the lambda, I wish to add a specific condition if the exception is of ArgumentException type. Is there any way to identify which specific type of exception was thrown? Checking the type with 'is' keyword is not working as given by this link

FYI, a custom ServiceRunner is implemented for the servicestack instance that we use.

Upvotes: 0

Views: 47

Answers (1)

ronilk
ronilk

Reputation: 372

The piece of code that caused the ArgumentException was

return serializer.Deserialize(querystring, TEMP);

For some reason, the exception object cannot be recognised as an ArgumentException inside the ExceptionHandler

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

Although, as mentioned in the link(pls refer question) the InnerException can be identified using is keyword.

Hence the solution applied was to throw the ArgumentException as an inner exception as follows:

public const string ARG_EX_MSG = "Deserialize|ArgumentException";

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

Hence, now the ExceptionHandler code is:

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

Upvotes: 0

Related Questions