The developer exception page

The MVC middleware of ASP.NET Core comes with a built-in developer exception page that is aimed at providing meaningful information while you're in development mode. When you created your ASP.NET Core project, Visual Studio automatically generated the code that enables the usage of the developer exception page inside the Configure method of the Startup class:

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
How does ASP.NET Core determine that you are in development mode? ASP.NET uses an environment variable by the name of ASPNETCORE_ENVIRONMENT. If its value is Development, then the IsDevelopment method returns true. You can control the value of the ASPNETCORE_ENVIRONMENT environment variable for each of the profiles you run the application in through the Debug tab in the project properties screen:



Ultimately, these configurations are saved in the launchSettings.json file, located under the Properties folder of your project, so alternatively, you can edit this file and get the same effect. 

To test the developer exception page, I've added a new action in the ProdcutsController class that simply throws an exception to simulate an unhandled exception situation:

[AllowAnonymous]
[HttpGet("error")]
public ActionResult ThrowError()
{
throw new InvalidOperationException("This is an example of unhandled exception");
}

Run the application and navigate your browser to http://localhost:{port}/api/products/error. You should see a page similar to this:

The text in this image is not important. The purpose of this image is to show what an error page will look like when it occurs.

The page includes the stack trace and the message of the thrown exception, as well as the request details, such as the query string, cookies, and headers that were sent.

As useful to the developer as this may be, it's unpractical for usage when dealing with Web APIs, because the caller of the API is not a browser that can render an HTML output. For example, here is the response that Postman shows after sending the request to the error action:

Developers, including yourself, will have a hard time deciphering the content, and even if you manage to do so, the application that talks with your API can receive those errors in runtime and won't be able to extract the needed information to write to a log or explain to you what the problem was.

The bottom line is that, when developing a Web API, you should avoid usage of the developer exception page, and add another mechanism to deal with unhandled exceptions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.139.15