44

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
  • 98,240
  • 88
  • 296
  • 433
Alvin
  • 8,219
  • 25
  • 96
  • 177

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,483
  • 13
  • 50
  • 76
Filip W
  • 27,097
  • 6
  • 95
  • 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
  • 615
  • 1
  • 7
  • 19
Youssef Moussaoui
  • 12,187
  • 2
  • 41
  • 37