简体   繁体   中英

ASP.NET Web API return HttpResponseMessage or throw error

I've been looking into writing a web service using the .net Web APIs, but I'm seeing two different approaches to sending error messages. The first is to return an HttpResponseMessage with the appropriate HttpStatusCode set, something like this:

public HttpResponseMessage<string> Get() 
{ 
      ...
      // Error!
      return new HttpResponseMessage<string>(System.Net.HttpStatusCode.Unauthorized); 
}

And the other method is to just throw an HttpResponseException , like this:

public Person Get(int id)
{
     if (!_contacts.ContainsKey(id))
     {
         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, String.Format("Contact {0} not found.", id)));
     }

     return _contacts[id];
}

Are there any advantages/disadvantages to using either one? And in terms of scalability and performance, is either one better than the other?

In case anyone is curious which direction I went, I went with HttpResponseException for several reasons:

  • It makes the code more readable to someone who is not as familiar with WebAPIs (Most people know that when you throw an exception, something went wrong)
  • In my tests HttpResponseExceptions return faster, YMMV
  • It's easier to Unit Test (just Assert that an exception was thrown)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM