Monday, October 10, 2022

How to Handle Exception in Asp.NET MVC

 5 Ways to do MVC Error Handling

  1. Web.Config customErrors
  2. MVC HandleErrorAttribute
  3. Controller.OnException method
  4. HttpApplication Application_Error event
  5. Collect exceptions via .NET profiling with Retrace.

There are two critical things that you need accomplish with error handling:

  1. Gracefully handling errors and show your users a friendly error page
  2. Logging errors so that you are aware of them and can monitor them

  1. Web.Config customErrors:

<system.web>
    <customErrors mode="On" defaultRedirect="~/ErrorHandler/Index">
        <error statusCode="404" redirect="~/ErrorHandler/NotFound"/>
    </customErrors>
<system.web/>


There are several ways to do MVC error handling. You should always specify a default error page via your web.config <customErrors> and log unhandled exceptions that get called back to your HttpApplication Error method.

You can use HandleErrorAttribute or OnException to provide fine-grained control of how you display error type messages to your users.

If you want to track all of your application exceptions, be sure to check our Retrace and our error monitoring features. You can also view all application exceptions on your workstation for free with our free profiler, Prefix.




No comments:

Post a Comment