0

I am using MVC4, and would like to be able to throw HttpExceptions from a ontroller, and handle those in a seperate controler.

I have set up <customErrors mode="On" defaultRedirect="/Error"/> for this. This works, but in my controller I would like to be able to access the exception.

Preferably I would like to have two modes:

  1. Handle instances of HttpException, so that from a controller I can throw a HttpException and have it handled accordingly

  2. Handle all other errors.

in case of the first, I would like to present the useragent with the appropriate status code, and possibly a view. In case of the second I want to present the useragent with status 500, and show a default view with an optional message.

For this, I think I need to access the exception data - at least, I can't think of any other proper way to do this.

What is the proper way to set this up? I know there are plethoria of other questions on error handling in MVC, yet none seem to answer these questions.

Martijn
  • 11,183
  • 10
  • 46
  • 92

1 Answers1

1
 but in my controller I would like to be able to access the exception.

Have you tried Server.GetLastError:

Exception ex = Server.GetLastError();

Server.GetLastError() - should be used in Application_Error in global.asax, in that case you can handle last error like described here, besides you should remove

filters.Add(new HandleErrorAttribute());

in FilterConfig.cs

for more info look at:

Application_Error not firing when customerrors = "On"

ASP.NET custom error page - Server.GetLastError() is null

http://www.secretgeek.net/custom_errors_mvc.asp

http://devstuffs.wordpress.com/2010/12/12/how-to-use-customerrors-in-asp-net-mvc-2/

Community
  • 1
  • 1
testCoder
  • 6,587
  • 13
  • 49
  • 72