45

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?

2 Answers 2

76

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"));
    }
Sign up to request clarification or add additional context in comments.

2 Comments

But when I host it to the web server, I always get a HTTP 500 error.
@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");
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.