I have a c# application that sends requests to several API's, but earlier today one of them seemed to be down for a while and caused an exception within my exception handler:
catch (WebException e)
{
var statusCode = ((HttpWebResponse)e.Response).StatusCode;
//Use status code and exception for reporting and handling.
}
This caused a problem because at the time, the Exception did not have a Response
, so I was trying to get the StatusCode of nothing, and a NullPointerException was thrown.
I've since changed it to this in order to try and get the status code if there's no response (I didn't use the response for anything other than the status code anyway).
catch (WebException e)
{
//Try to get the status code from the exception, can fail somehow.
HttpStatusCode statusCode;
try
{
statusCode = (HttpStatusCode)e.Status;
}
catch(Exception innerE)
{
//Capture exceptions for logging
//...
//Set a default code to continue.
statusCode = HttpStatusCode.InternalServerError;
}
//Use status code and exception for reporting and handling.
}
From this answer it looks like you can try for both the status from the response and the status from the exception.
My question is if I should try for both or if one would be set over another?
For example, in order to test the code I'm using now, I was able to manually throw a WebException with just the status and no response.
Could there be any instance where I'd get a response with no status on the exception? Or if there could be a situation where the status code from the response would be more detailed or different from the status code straight from the exception itself?
I am making the call with a basic HttpWebRequest
.
Update:
The API that I interact with I don't have control over and it wasn't until the failure happened today that I found out it was possible to come back with no response. I set it manually to the 500 for my own error handling further down in the catch block, my users don't know that's what I use. I'm just asking if one way of retrieving the StatusCode is better/different than another way. Or if I shouldn't rely on one method over another, and if I should try both and which to prefer?