42

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?

abatishchev
  • 95,331
  • 80
  • 293
  • 426
Alvin
  • 7,787
  • 23
  • 77
  • 164

2 Answers2

75

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"));
    }
Divyang Desai
  • 7,055
  • 13
  • 45
  • 69
Filip W
  • 26,907
  • 6
  • 92
  • 82
  • 2
    But when I host it to the web server, I always get a HTTP 500 error. – Alvin Jan 30 '13 at 23:13
  • @Alvin Are you inheriting your controller from ApiController? Also check if this GetTestId method is NOT called from a constructor, just to be sure. If everything fails, try the following to throw the error: throw new HttpException((int)HttpStatusCode.NotFound,"this item does not exist"); – Ε Г И І И О Jan 06 '20 at 04:21
6

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.

Osama Rizwan
  • 599
  • 1
  • 6
  • 19
Youssef Moussaoui
  • 11,874
  • 2
  • 39
  • 35