I have a web API that makes HTTP requests to a Windows service that performs certain tasks / commands.
If my βserviceβ throws an exception, I want to pass that exception back to the web API using JSON. Then I want to de-serialize the exception back to the exception object and throw it away.
my code is:
General 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 am returning a JSON object. Either the response object or the Exception that happened to it.
Then here is the code in the web API that 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, if the response was successful, I simply return the contents of the string. If the request fails, I try to pass the json response to the exception. However, I have to pass it to the basic exception, as I do - I donβt know what type it is yet. However, when I debug and add a watchdog to the exception. There is a _className parameter that states: "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 various exceptions, increasing the level of my services in the web API.
Here is a json example that is returned for ConnectionErrorException :
{ "ClassName": "Domain.Model.Exceptions.API.ConnectionErrorException", "Message": null, "Data": null, "InnerException": null, "HelpURL": null, "StackTraceString": "", "HResult": -2146233088, "Source": "LinkProvider.Logic", "WatsonBuckets": null }