We’ve reviewed what happens if an exception is thrown when the application is running in a development environment. We’ve also discussed how the developer exception page reveals a substantial amount of information about the application. Now, let’s take a moment to see what should happen if an exception is thrown while the application is running in a production environment.
Exceptions will happen in every application, but the proper handling of exceptions can prevent an unnecessary security vulnerability. We never want to expose essential details about our application to users. If an exception is thrown in a production environment, one way of handling it is to show users a general error page. Thankfully, ASP.NET has a built-in middleware component to do this.
UseExceptionHandler() component can be used in production environments. It will catch and log errors and route users to a general error page. The error page can be customized but the significant detail is that this is a way to notify users that an issue has occurred while still hiding the internal details of our application.
UseExceptionHandler() component has several overloads, but a simple way of using it is to pass in the name of the page (as a string) that should display if an exception is thrown. In the previous exercise, we talked about using conditional logic to determine if the application is running in a development environment. We can add an
else clause so that if the development environment conditional returns false (i.e. the application is NOT in development) then we call the
Navigate to the Contact page by clicking the
Contact Us button. An exception will be thrown.
Typically, the environment variable is set in an
appSettings file. In this case, we’ve hardcoded the environment variable to production so we can test the
else clause to the
if statement that checks to see if the application is running in development.
Within the else clause, call the
UseExceptionHandler() component and pass in the string “/Error” as an argument. This will tell the application to route to the default error page if an exception is thrown in production.