How to throw exception in Web API?

前端 未结 2 438
滥情空心
滥情空心 2020-12-13 23:38

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 (t         


        
相关标签:
2条回答
  • 2020-12-14 00:28

    This should help you understand WebAPI error handling a bit better:

    http://blogs.msdn.com/b/youssefm/archive/2012/06/28/error-handling-in-asp-net-webapi.aspx

    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.

    0 讨论(0)
  • 2020-12-14 00:29

    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"));
        }
    
    0 讨论(0)
提交回复
热议问题