Alvin Alvin - 28 days ago 15
C# Question

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?

Answer

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"));
    }