这篇文章主要为大家详细介绍了asp.net core异常和错误处理的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
在这一章,我们将讨论异常和错误处理。当 asp.net core应用程序中发生错误时,您可以以各种不同的方式来处理。让我们来看看通过添加一个中间件来处理异常情况,这个中间件将帮助我们处理错误。
要模拟出错,让我们转到应用程序,运行,如果我们只是抛出异常的话,看看程序是如何运转转的。
using microsoft.aspnet.builder;
using microsoft.aspnet.hosting;
using microsoft.aspnet.http;
using microsoft.extensions.dependencyinjection;
using microsoft.extensions.configuration;
namespace firstappdemo {
public class startup {
public startup() {
var builder = new configurationbuilder()
.addjsonfile("appsettings.json");
configuration = builder.build();
}
public iconfiguration configuration { get; set; }
// this method gets called by the runtime.
// use this method to add services to the container.
// for more information on how to configure your application,
// visit http://go.microsoft.com/fwlink/?linkid=398940
public void configureservices(iservicecollection services) {
}
// this method gets called by the runtime.
// use this method to configure the http request pipeline.
public void configure(iapplicationbuilder app) {
app.useiisplatformhandler();
app.useruntimeinfopage();
app.run(async (context) => {
throw new system.exception("throw exception");
var msg = configuration["message"];
await context.response.writeasync(msg);
});
}
// entry point for the application.
public static void main(string[] args) => webapplication.run<startup>(args);
}
}
它只会抛出一个非常通用的异常信息。保存startup.cs页面并运行您的应用程序。
您将看到我们未能加载此资源。出现了一个 http 500 错误,内部服务器错误,那个页面不是很有帮助。它可能很方便得到一些异常信息。
让我们添加另一个中间件 usedeveloperexceptionpage。
// this method gets called by the runtime.
// use this method to configure the http request pipeline.
public void configure(iapplicationbuilder app) {
app.useiisplatformhandler();
app.usedeveloperexceptionpage();
app.useruntimeinfopage();
app.run(async (context) => {
throw new system.exception("throw exception");
var msg = configuration["message"];
await context.response.writeasync(msg);
});
}
这个中间件与其他的有点不同,其他中间件通常监听传入的请求并对请求做一些响应。
usedeveloperexceptionpage不会如此在意传入的请求在之后的管道会发生什么。
它只是调用下一个中间件,然后再等待,看看管道中是否会出现异常,如果有异常,这块中间件会给你一个关于该异常的错误页面。
现在让我们再次运行应用程序。将会产生一个如下面的屏幕截图所示的输出。
现在如果程序中出现异常,您将在页面中看到一些想要看到的异常信息。你也会得到一个堆栈跟踪:这里可以看到startup.cs第37行有一个未处理的异常抛出。
所有这些异常信息对开发人员将非常有用。事实上,我们可能只希望当开发人员运行应用程序时才显示这些异常信息。
以上就是asp.net core异常和错误处理(8)_实用技巧的详细内容。