Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between HttpResponseException and HttpException

Tags:

asp.net-mvc

From http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

HttpResponseException

What happens if a Web API controller throws an exception? By default, most exceptions are translated into an HTTP response with status code 500, Internal Server Error.

The HttpResponseException type is a special case. This exception returns any HTTP status code that you specify in the constructor of the exception.

Except that it doesn't. Fiddler shows me a 500 is returned.

However, HttpException seems to do what that article says.

Is the documentation wrong or am I missing something?

UPDATE

While typing that out, I had an idea. I tried both from two controllers, an ApiController and a standard MVC controller.

The two exception work in reverse to each other depending on the type of controller they're thrown from.

  • Use HttpResponseException to return a proper HTTP code from an API controller.
  • Use HttpException to return a proper HTTP code from an MVC controller.
like image 995
Luke Puplett Avatar asked Jun 27 '12 11:06

Luke Puplett


People also ask

What makes it different a Web API routing from MVC routing?

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.

What are the different ways to handle errors in Web API?

You can customize how Web API handles exceptions by writing an exception filter. An exception filter is executed when a controller method throws any unhandled exception that is not an HttpResponseException exception.

What is IHttpActionResult C#?

IHttpActionResult contains a single method, ExecuteAsync, which asynchronously creates an HttpResponseMessage instance. C# Copy. public interface IHttpActionResult { Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken); }

What is exception handling in asp net?

In the . NET Framework, an exception is an object that inherits from the System. Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception.


1 Answers

[Moved my update to an answer]

While typing that out, I had an idea. I tried both from two controllers, an ApiController and a standard MVC controller.

The two exception work in reverse to each other depending on the type of controller they're thrown from.

  • Use HttpResponseException to return a proper HTTP code from an API controller.
  • Use HttpException to return a proper HTTP code from an MVC controller.
like image 105
Luke Puplett Avatar answered Oct 09 '22 00:10

Luke Puplett