Asp.net-core-exceptions
提供:Dev Guides
ASP.NET Core-例外
この章では、*例外とエラー処理*について説明します。 ASP.NET Coreアプリでエラーが発生した場合、さまざまな方法でエラーを処理できます。 診断パッケージを通じて利用可能な追加のミドルウェアを見てみましょう。 このミドルウェアは、エラーの処理に役立ちます。
エラーをシミュレートするには、 app.Run に移動して、このミドルウェアをヒットするたびに例外をスローするだけの場合のアプリケーションの動作を確認しましょう。
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行目に未処理の例外がスローされたことを確認できます。
また、未加工の例外の詳細を確認することもでき、この情報はすべて開発者にとって非常に役立ちます。 実際、開発者がアプリケーションを実行しているときにのみ、この情報を表示したいでしょう。