Question
When should `customErrors` be used versus global exception handlers in ASP.NET (e.g., `Application_Error` in Global.asax)?
Asked by: USER1257
122 Viewed
122 Answers
Answer (122)
Both `customErrors` and global exception handlers serve distinct but complementary roles in error management:
- **`customErrors` in `web.config`:** Primarily handles the *display* of user-friendly error pages for unhandled exceptions. Its main purpose is to prevent users from seeing raw, detailed error messages. It redirects the user to a static or dynamic error page, and the original HTTP status code is typically preserved for non-absolute redirects. It's a configuration-driven approach for presenting errors.
- **Global Exception Handlers (e.g., `Application_Error` in Global.asax or `IExceptionHandler` in modern ASP.NET):** These are code-driven mechanisms designed for *logging, processing, or further handling* unhandled exceptions before `customErrors` takes over for display. In `Application_Error`, you can access the exception details (`Server.GetLastError()`), log it to a database or file, notify administrators, and then optionally clear the error (`Server.ClearError()`) to allow normal page processing or let `customErrors` take effect.
**Best Practice:** Use `Application_Error` (or similar code-based handlers) for logging and programmatic handling of errors, and then rely on `customErrors` to display a user-friendly page. This separation ensures errors are properly recorded for analysis while users get a good experience.