Confused with error handling in ASP.net 5 MVC 6

I would like to have 1 error page, which, depending on the query line, displays a slightly different error message to the user.

I noticed the following code in the Startup.cs file when creating a new asp.net 5 project.

if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } 

I was able to get this to display the correct error page when an exception occurs. My problem is that they seem to catch errors that were not handled in my application, i.e. always with a status code of 500 . It's right?

To handle 404 errors, I use the following code:

 app.UseStatusCodePagesWithReExecute("/Error/{0}"); 

With my controller implemented as:

 [HttpGet("{statusCode}")] public IActionResult Error(int statusCode) { return View(statusCode); } 

It seems to catch 404 errors and display the correct status code.

If I update my code in the above if statement to use the same action, for example:

 if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error/{0}"); } 

The returned status code is always 0.

Also, what happens when a 400 , 403 or whatever happens? Will they be caught? If so, at what point will they be caught?

As you can tell, I am very confused and would like someone to provide me with an example where all the different status codes are processed.

+7
c # exception asp.net-core asp.net-core-mvc
source share
1 answer

It looks like you are confusing unhandled exceptions (which by default are returned to the client as an internal HTTP 500 server error) and correctly handled errors caused by invalid actions on behalf of the user / client (where the HTTP 4xx code is returned for the user).

Only the first one has anything to do with calling UseExceptionHandler - by default it will catch any unhandled exceptions and direct them to everything that you provide (in your case, a view, but it can also be easily code that checks unhandled exceptions for converting certain errors to HTTP 4xx return codes - for example, authentication errors to HTTP 401 responses).

UseStatusCodePagesWithReExecute will enter where the status code was generated 400-599, provided that the response body has already been created. The source code shows how this is defined.

In your second block of code, you used UseExceptionHandler - I think you should have the following:

 if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { // Handle unhandled errors app.UseExceptionHandler("/Home/Error"); // Display friendly error pages for any non-success case // This will handle any situation where a status code is >= 400 // and < 600, so long as no response body has already been // generated. app.UseStatusCodePagesWithReExecute("/Error/{0}"); } 
+18
source share

All Articles