本文主要介绍ASP.NET Core中使用中间件(Middleware)进行异常处理,捕获网站请求中的异常信息并且返回给调用者。

1、中间件(Middleware)拦截所有的异常并返回给调用者

public class ExceptionHandler
{
    private readonly RequestDelegate _next;
    public ExceptionHandler(RequestDelegate next)
    {
        _next = next;
    }
    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }
    private async Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var response = context.Response;
        response.ContentType = "application/json";
        response.StatusCode = (int)HttpStatusCode.InternalServerError;
        await response.WriteAsync(JsonConvert.SerializeObject(new
        {
            // customize as you need
            error = new
            {
                message = exception.Message,
                exception = exception.GetType().Name
            }
        }));
    }
}

2、在Startup.cs中Configure方法中配置

public void Configure(IApplicationBuilder app, IHostingEnvironment env, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
{
    loggerFactory.AddNLog();
    env.ConfigureNLog(Path.Combine(AppContext.BaseDirectory, "nlog.config"));

    if (env.IsDevelopment())
        app.UseDeveloperExceptionPage();
    else
        app.UseMiddleware<ExceptionHandler>();
    app.UseMvc();
}

推荐文档