。Net Core MVC在视图上显示异常错误

问题描述 投票:0回答:1

[基本上,我正在寻找一种管理异常的方法,该异常已在服务层中抛出并显示在当前View上,类似于ModelState。但是我正在努力做这种事情的正确方法。我真的不想在抛出异常的控制器的每个动作中添加try-catch。有什么全球性的方法吗?这是我由于运气不好而已经做的不多的原因:用户提供的凭证被抛出错误的异常ExceptionHandlingMiddleware抓住了它但是我不知道现在该怎么办,在ExceptionHandlingMiddleware中我可以访问HttpContext,但我不知道这将以任何方式帮助我。我应该使用JavaScript来捕获此HttpContext可以提供的响应,还是应该以某种方式使用ViewComponent?服务层操作通常不返回任何内容,因此我无法继续执行该操作。例外:throw new Exception("Wrong credentials");ExceptionHandlingMiddleware(目前更可能是占位符)代码:

public static class ExceptionHandlingMiddlewareExtension
    {
        public static IApplicationBuilder UseExceptionHandlingMiddleware(this IApplicationBuilder app)
        {
            return app.UseExceptionHandler(options =>
            {
                options.Run(async context =>
                {

                });
            });
        }
    }
asp.net-core exception model-view-controller view core
1个回答
0
投票

一种方法是使用in-built Exception handler page。您还可以使用自定义ExceptionHandler中间件来捕获异常并返回页面:

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
            }
        }));
    }
}

或使用HandleExceptionAsync使用模型重定向到context.Response.Redirect("/Home/Errorpage");中的自定义页面。最后注册中间件:

app.UseMiddleware<ExceptionHandler>();
© www.soinside.com 2019 - 2024. All rights reserved.