core hands-on item (09) - exception handling

This article explains the technical essentials related to core exception handling.

Configuring the core development environment core divides the development environment for Web applications into Development, Staging, and Production. These different environments mean self-describing and are no longer explained. In a development environment, when an exception occurs, core uses a uniform template to display the exception, including Stack trace,For example, trying to access an exception page whose Id is 111 shows the following:

If such a page is also displayed in a production environment, it is not only user-masked but also extremely unsafe. So we need to handle typical exceptions and provide friendly pages.

However, in the development environment, these custom exception handling pages do not appear because core defines uniform exception handling. In the startup.cs file, there is a section of code below:

In core, the IWebHostEnvironment interface automatically recognizes the locally defined development environment controlled by the ASPNETCORE_ENVIRONMENT environment variable. ASPNETCORE_ENVIRONMENT can be defined in the environment variable, or in the lauchsettings.json file below the project file Properties.Definitions in the file have a higher priority. If neither environment variables nor lauchsettings.json files are defined, the default settings are not Production.

Visual Studio 2019 provides an interface for setting lauchsettings.json by selecting the project name, right-clicking the mouse, selecting Properties, and displaying the following interface:

Select Profile as StudentManagemnt and change the value of Environment variables to Production.

The advantage of this is that if you want to see unusual pages in your local development environment, you only need to run with StudentManagement, the so-called Kestrel hosting.

The changes you just made in the interface are actually recorded in the lauchsettings.json file:

After setting the environment variable, make the following modifications to the Configure() method in the startup.cs file:

404 Errors and Unified Processing

404 - Page not found ation is the most common exception. There are two reasons for this exception: first, the resource with the specified Id cannot be found, such as the example just given, trying to access the student information with Id 111, but the Id does not exist; second, the requested URL does not match the route.

For the first type of resource that cannot find the specified Id, you can set exception pages specifically for it. First, in the StudentController.cs file, rewrite the Details() Action method to:

public IActionResult Details(int id)
    var student = repository.GetStudent(id);
    if (student != null) {
        ViewBag.PageTitle = "Student Information List";
        return View(student);
    else {
        Response.StatusCode = 404;
        return View("StudentNotFound", id);

Define the StudentNotFound razor view in the Views / Student folder:

@model int

    ViewBag.Title = "404 error";

<div class="card text-white bg-secondary mb-3" style="width: 80rem;">
    <div class="card-body">
        <h2 class="card-title">404 not found</h2>
        <p class="card-text">Unable to Query Students ID by @Model Information</p>
        <a class="btn btn-primary" asp-action="index">Return to Student Information List</a>

At this point, for students who cannot find Id, the page shows as follows:

A new Controller, named ErrorController, defines the HandleError() method in ErrorController to handle routes specified by the Configure() method in the Startup.cs file:

public IActionResult HandleError(int code)
    ViewData["ErrorMessage"] = $"Error occurred. The ErrorCode is: {code}";
    return View("~/Views/Error/404.cshtml");

Then create a 404.cshtml Razor view file under the Views / Error folder:

<div class="middle-box text-center animated fadeInDown">
    <h3> Page not found!! !</h3>
        The page you entered does not exist!
            <a class="btn btn-primary" asp-controller="student" asp-action="index">Home</a>

In this way, various user input paths are incorrect, and they all display as:

Global exception handling

Exceptions to core may come from incorrect requests from users or from other layers such as Repository, Service, etc. We can define exceptions to capture the whole project in the Controller, handle them uniformly, and increase the friendliness of the interface and robustness of the program. First, add Error() to the ErrorController.When an error or exception occurs, it is displayed in the Error view:

public IActionResult DefaultHandler()
    // Get exception information
    var e = HttpContext.Features.Get<IExceptionHandlerPathFeature>();
    ViewBag.ExceptionPath = e.Path;
    ViewBag.ExceptionMessage = e.Error.Message;
    ViewBag.StackTrace = e.Error.StackTrace;
    return View("Error");

In the Views / Error folder, create a new Error.cshtml view:

    There was a rough problem in the program request. We're working hard to solve it. It's a bit big. Please bear with it.
<br />

<h3>Error Details</h3>
<div class="alert alert-default-light">
    <h6>Exception path:</h6>
    <hr />

<div class="alert alert-default-warning">
    <h6>Exception information:</h6>
    <hr />

<h6>Emergency please go through mailbox Contact us!</h6>

Recall that in the Startup.cs file, we used the UseExceptionHandler middleware and set the route to/Error so that it can be triggered when an exception occurs in ErrorController. To make it clearer how the exception is triggered, I created a new OnpurposeError() method in StudentController to indicate an intentional error:

public IActionResult OnpurposeError()
    throw new Exception("An unknown error occurred");

Running the program triggers a set exception when url path is/Student/OnpurposeError:

Source code

The source code is hosted on gitee, In order to record the complete writing process, important steps are to submit tags for easy viewing and comparison. The code tag is v0.09. You can see the corresponding code through git checkout v0.09.

Reference resources

Handle errors in ASP.NET Core | Microsoft Docs

Keywords: ASP.NET html mvc

Added by internet-solution on Sat, 25 Sep 2021 20:08:38 +0300