How to throw exception in Web API?
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"));
}
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
.