In the Web API that I'm working with, I have several conditions I'm checking for before I send JSON response to the calling program.
One way I have handled errors is to return something like this:
return Content(HttpStatusCode.NotFound, "This user reached maximum API calls for today.", new JsonMediaTypeFormatter(), "application/json");
When I tested the API using something like this:
var result = new System.Net.WebClient().DownloadString("BadURL");
I get an unhandled Exception error, which is expected.
To get around this, I change return statement in my error handling logic to something like this:
return Content(HttpStatusCode.OK, "This user reached maximum API calls for today.", new JsonMediaTypeFormatter(), "application/json");
So even the user uses the same WebClient() above, they get a useful error message (this and other error messages are well documented on the website) and no Exception.
Is this a good way of handling errors in ASP.NET Web API?
I think you should probably make your API modeled around standard status codes. (You shouldn't return a 200 when there was an error).
Here are some common used status codes for REST API http://www.restapitutorial.com/httpstatuscodes.html
The issue you're seeing is just that WebClient throws exceptions on lots of status codes (404 for example). I don't think your api should revolve around making WebClient not throw exceptions. You can wrap the WebClient in try catch and grab the WebException and get the status code and error message from there.
(not tested code, but something similar to this)
try
{
var result = new System.Net.WebClient().DownloadString("BadURL");
// process result
}
catch (WebException webEx)
{
var statusCode = ((HttpWebResponse)webEx.Response).StatusCode;
var body = new StreamReader(webEx.Response.GetResponseStream()).ReadToEnd();
switch (statusCode)
{
case 404:
// parse error from your body (or in your case it is your body)
case ...:
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With