How to customize Developer Exception Page in Asp.Net Core?

岁酱吖の 提交于 2019-12-12 11:01:49

问题


It's common in the Configure method of the Startup.cs file to have code that looks like this:

if(env.IsDevelopment()) {
     app.UseDeveloperExceptionPage();
} 

The app.UseDeveloperExceptionPage(); line causes detailed information to be displayed in the browser when an exception occurs which is quite helpful for debugging.

I'm sure you've seen the output, it looks something like this:

This is a great start, but sometimes as developers we add additional information to exceptions to provide details about the error. The System.Exception class has a Data collection that can be used for storing such information. So for example my custom AppException that inherits from Exception has a constructor that accepts a private message in addition to the standard exception message, like so:

 /// <summary>
 /// Application Exception. 
 /// </summary>
 /// <param name="message">Message that can be displayed to a visitor.</param>
 /// <param name="privateMessage">Message for developers to pinpoint the circumstances that caused exception.</param>
 /// <param name="innerException"></param>
    public AppException(string message, string privateMessage, Exception innerException = null) 
        : base(message, innerException) {

        //Placing it in the exception Data collection makes the info available in the debugger
        this.Data["PrivateMessage"] = privateMessage;
    }

So as you can imaging, it'd be nice if the developer exception page displayed the PrivateMessage from the Exception (if it's an AppException) along with all the other information. I've looked high and low to figure out how to customize or augment the information displayed on the developer exception page but haven't been able to find any good information on it.

How can I customize or augment the information displayed on the developer exception page?


回答1:


The app.UseDeveloperExceptionPage() extension method is shorthand for adding the DeveloperExceptionPageMiddleware into the request/response pipeline. You can find the full source code for DeveloperExceptionPageMiddleware here, including the middleware itself and the views. It should make an excellent base for rolling your own custom middleware.




回答2:


The DeveloperExceptionPageMiddleware has the design problem - it assumes that all exceptions are 500 and it starts sending the response right away. It means, it's impossible to correct the behavior of this middleware by applying another custom middleware on top of that.

So, there are two options: replicate its nice HTML error page generation in your code or create your own dev exception page (I'd advise to dump current exception and the context in JSON and return it to the client).



来源:https://stackoverflow.com/questions/41882493/how-to-customize-developer-exception-page-in-asp-net-core

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!