How can I throw a exception to in ASP.net Web Api?
Below is my code:
public Test GetTestId(string id)
{
Test test = _test.GetTest(id);
if (test == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return test;
}
I don't think I am doing the right thing, How do my client know it is a HTTP 404
error?
What you have in your code snippet should work. The server will send back a 404 Not Found to the client if test is null with no response body. If you want a response body, you should consider using Request. CreateErrorResponse as explained in the blog post above and passing that response to the HttpResponseException .
Exception handling is the technique to handle this runtime error in our application code. If any error is thrown in web API that is caught, it is translated into an HTTP response with status code 500- "Internal Server Error". There are many ways to handle the exception.
BadRequest: 400 Error A 400 error, BadRequest, is used when you have validation errors from data posted back by the user. You pass a ModelStateDictionary object to the BadRequest method and it converts that dictionary into JSON which, in turn, is passed back to your HTML page.
Global Exception Filters With exception filters, you can customize how your Web API handles several exceptions by writing the exception filter class. Exception filters catch the unhandled exceptions in Web API. When an action method throws an unhandled exception, execution of the filter occurs.
It's absolutely fine.
Alternatively, if you wish to provide more info (to allow, as you say, the client to distinguish from regular 404):
if (test == null)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound,
"this item does not exist"));
}
This blogpost should help you understand WebAPI error handling a bit better.
What you have in your code snippet should work. The server will send back a 404 Not Found to the client if test is null with no response body. If you want a response body, you should consider using Request.CreateErrorResponse
as explained in the blog post above and passing that response to the HttpResponseException
.
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