Handling global exceptions
As mentioned earlier in this chapter, we can only handle so many errors when it comes to web applications. But what if we want to provide a catch-all for all unhandled exceptions?
For global exceptions, we need to revisit the middleware. There is a method called UseExceptionHandler() in the Startup.cs file that points to a /Error page (either Razor or MVC), as shown in the following code snippet:
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
} Pay particular attention to the env.IsDevelopment() condition. The /Error page is meant for non-development viewing only. As we mentioned back in Chapter 4 regarding security, always be careful what to show on this page. It may expose system data such as a database connection string that contains credentials or other sensitive data.
To access the exception...