I have a Web API which makes HTTP Requests to a windows service that executes certain tasks/commands.
If my 'service' throws an exception I then want to pass that exception back up the pipe to the Web API using JSON. I then want to de-serialize the exception back to an exception object and throw it.
my code:
Shared exception between Web API and Service:
public class ConnectionErrorException : Exception
{
public ConnectionErrorException()
{
}
public ConnectionErrorException(String message)
: base(message)
{
}
}
Now in my Service I have the following code:
...
try
{
result = await ExecuteCommand(userId);
//If reached here nothing went wrong, so can return an OK result
await p.WriteSuccessAsync();
}
catch (Exception e)
{
//Some thing went wrong. Return the error so they know what the issue is
result = e;
p.WriteFailure();
}
//Write the body of the response:
//If the result is null there is no need to send any body, the 200 or 400 header is sufficient
if (result != null)
{
var resultOutput = JsonConvert.SerializeObject(result);
await p.OutputStream.WriteAsync(resultOutput);
}
...
So here I return a JSON object. Either the actual response object, or the Exception which happened to occour.
Then here is the code in the Web API which makes the request to the Service:
// Make request
HttpResponseMessage response = await client.PostAsJsonAsync(((int)(command.CommandId)).ToString(), command);
if (response.IsSuccessStatusCode)
{
return await response.Content.ReadAsStringAsync();
}
else
{
var exception = HandleErrorResponse(await response.Content.ReadAsStringAsync());
var type = exception.GetType();
//TODO: try and determine which exact exception it is.
throw exception;
}
Now here, if the response was successful I just return the string content. If the request fails, I try and pass the json response to an exception. However I have to pass it to the base exception as I do-not know what type it is yet. However when I debug and add a watchdog on the exception. There is a parameter _className which says 'Domain.Model.Exceptions.API.ConnectionErrorException`.
Question: How can I determine which exception was returned and de-serialize it back to the correct exception so that I can throw it again. I need to know the exact type of exception because I handle all the different exceptions further up my services layer in the Web API.
Here is an example of the json which is returned for the ConnectionErrorException:
{
"ClassName": "Domain.Model.Exceptions.API.ConnectionErrorException",
"Message": null,
"Data": null,
"InnerException": null,
"HelpURL": null,
"StackTraceString": "",
"HResult": -2146233088,
"Source": "LinkProvider.Logic",
"WatsonBuckets": null
}