In this lesson, you will learn how to configure custom error pages and implement global exception logging to ensure your Razor Pages application remains resilient and user-friendly.
When an unexpected exception occurs, showing a raw stack trace to a user is a security risk and a poor experience. Instead, we want to intercept these crashes, log the diagnostic details for our developers, and show a polished, branded error page to the user.
Configuring the Error Pipeline
In your Program.cs file, you control how the application behaves when it encounters a 500 status code or an unhandled exception. For production environments, you should disable detailed developer exceptions and redirect users to a custom page:
if (!app.Environment.IsDevelopment())
{
// Redirects to /Error on exceptions
app.UseExceptionHandler("/Error");
app.UseHsts();
}
Creating the Custom Error Page
By default, the ASP.NET Core project template creates an Error.cshtml file. You should modify this file to provide helpful instructions, like a button to return to the home page or a reference number for support. The page model should be designed to capture the request ID, which helps you correlate the user's experience with the logs on your server:
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
Implementing Global Logging
To ensure resilience, you must log the exception details before the user sees the error page. By using ILogger within your middleware or inside the OnGet method of your Error.cshtml.cs, you can capture the exact state of the application.
By centralizing this logic, you don't have to wrap every single Razor Page handler in try-catch blocks. Instead, you allow the pipeline to catch unhandled exceptions, log the Exception object, and serve the generic error view. This approach separates your business logic from your error-handling requirements, keeping your code clean and maintainable.
Key Takeaway: Use UseExceptionHandler in your startup configuration to gracefully catch unhandled exceptions and redirect users to a custom view while logging diagnostic data for backend analysis.