Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to throw exception in Web API?

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?

like image 846
Alvin Avatar asked Jan 30 '13 15:01

Alvin


People also ask

How do I throw an exception from Web API?

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 .

What is exception handling in Web API?

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.

How does Web API handle 400 error?

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.

How does Web API handle global exceptions?

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.


2 Answers

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"));
    }
like image 198
Filip W Avatar answered Oct 13 '22 19:10

Filip W


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.

like image 6
Youssef Moussaoui Avatar answered Oct 13 '22 21:10

Youssef Moussaoui