In my applications Web API
, I have an exception filter that suppose to catch any exception and transmit it to the client within a response wrapper class.
My goal is to make that exception transmit with the correct type, so the client can reconstruct and re-throw it.
Following is the code for exception catcher:
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
HttpStatusCode OutputHttpCode = HttpStatusCode.InternalServerError;
var exceptionType = actionExecutedContext.Exception.GetType();
if (exceptionType == typeof(InvalidIDException))
{
OutputHttpCode = HttpStatusCode.Unauthorized;
}
//this way of getting type didnt work for me either
//var exceptionType = typeof(RestErrorResponse<>).MakeGenericType(actionExecutedContext.Exception.GetType());
actionExecutedContext.Response = new HttpResponseMessage()
{
Content = new StringContent(JsonConvert.SerializeObject(
//this will not compile here, saying t is a variable but used like a type.
//If i use generic "Exception" instead everything is working fine,
//but it will be interpreted as generic exception on client side and
//could not be handled properly if i rethrow it directly
new RestErrorResponse<exceptionType> () //Exception will compile
{
Content = null,
Status = RestStatus.Error,
Exception = actionExecutedContext.Exception
}
),
System.Text.Encoding.UTF8, "application/json"),
StatusCode = OutputHttpCode
};
base.OnException(actionExecutedContext);
}
This is a class with generics I'm trying to put my exception into:
public class RestErrorResponse<E> :RestResponse<Object> {
public E myException { get; set; }
}
If i use a generic Exception in my "RestErrorResponse" class this is a JSON that gets created:
{
"Exception": {
"ClassName": "InvalidLoginException",
"Message": "Invalid User Name",
"Data": {},
"InnerException": null,
"HelpURL": null,
"StackTraceString": "....",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "....",
"HResult": -2147024809,
"Source": "DB",
"WatsonBuckets": null,
"ParamName": null
},
"Status": {
"Verbal": "Error",
"Code": 1074
},
"Content": null
}
My goal will be to get:
{
"InvalidLoginException": {
"ClassName": "InvalidLoginException",
"Message": "Invalid User Name",
"Data": {},
"InnerException": null,
"HelpURL": null,
"StackTraceString": "....",
"RemoteStackTraceString": null,
"RemoteStackIndex": 0,
"ExceptionMethod": "....",
"HResult": -2147024809,
"Source": "DB",
"WatsonBuckets": null,
"ParamName": null
},
"Status": {
"Verbal": "Error",
"Code": 1074
},
"Content": null
}