Exception handling in Asp.net Core 2.2/3.0(Part 6)


Exception handling is one of the common practice in any web application development. In all web technology we will do it different ways like in asp.net web form we were doing using global.aspx file, while in asp.net mvc we were doing using [HandleError] attribute.

But in asp.net mvc core there is separate way to handle the exception handling i.e. using exception handling middleware like app.UseDeveloperExceptionPage(); and app.UseExceptionHandler

If we will create any asp.net mvc core application by default this middleware will be present.

app.UseDeveloperExceptionPage(): It is used for displaying the user friendly exception on development environment. This will work as global exception handling. It is one of the cool feature of asp.net core.

Just to reproduce the exception i have written the code in HomeController like this

Now if we will run the application on Development Env, we will get the exception like this.

In the above screen shot we are getting the clear error message to fix the issue. This is very useful for developer to quickly fix the issue without debugging the application.

If the application has been deployed to Prod then we will get the custom error message like this
app.UseExceptionHandler(“/Home/Error”);

If we have to display the StatusCode of Error message then we can use this middleware like this

Now if we will run the code in Development and Prod Env we will get output like this

In the above image we are getting the status code 500. This method will display the status codes between 400 and 599 that do not have a body.

This is the magic of Middleware which is making our life easier to be more productive.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.