全局异常处理程序-重定向数据

时间:2019-02-28 13:22:48

标签: c# asp.net-core asp.net-core-mvc

我想问一下如何从异常处理程序重定向到ErrorPage控制器的操作Error,并将异常消息作为该方法的参数?

到目前为止,我已经尝试过了,但是控制器方法中的字符串为空

app.UseExceptionHandler(
options =>
 {
     options.Run(
     async httpcontext =>
     {
         httpcontext.Response.ContentType = "text/html";
         var ex = httpcontext.Features.Get<IExceptionHandlerFeature>();
         if (ex != null)
         {
             httpcontext.Items.Add.("error", ex.Error.Message);
             httpcontext.Response.Redirect("/Error/ErrorPage/");
         }
     });
});

对此进行了测试:

public IActionResult ErrorPage()
{
    var err = HttpContext.Items.ContainsKey("error") ? HttpContext.Items["error"] : "Error";
    // other logic
    return View("ExceptionView", err);
}

和这个:

public IActionResult ErrorPage(string error)
{
    // other logic
    return View("ExceptionView", error);
}

也尝试过这种方式:

app.UseExceptionHandler(
options =>
{
     options.Run(
     async httpcontext =>
     {
         httpcontext.Response.ContentType = "text/html";
         var ex = httpcontext.Features.Get<IExceptionHandlerFeature>();
         if (ex != null)
         {
             //httpcontext.Request.Path = "/Error/ErrorPage/";
             //httpcontext.Request.QueryString = new QueryString($"?error={ex.Error.Message}");

             await httpcontext.Response.WriteAsync(JsonConvert.SerializeObject(new
             {
                 error = ex.Error.Message
             }));

             httpcontext.Response.Redirect("/Error/ErrorPage/");
         }
     });
});

同时使用:使用和不使用[FromBody]

public IActionResult ErrorPage([FromBody] string error)
{
    // other logic
    return View("ExceptionView", error);
}

这就是整个控制器

public class Error : ControllerBase
{
    public Error(Context context)
    {
        _context = context;
    }

    public IActionResult ErrorPage([FromBody] string error)
    {
        return View("ExceptionView", error);
    }
}

1 个答案:

答案 0 :(得分:1)

这是我们的设置:

Startup.cs

public virtual void Configure(
        IApplicationBuilder app,
        IHostingEnvironment env,
        ILoggerFactory loggerFactory,
        IApplicationLifetime lifetime)
    {

        ... 

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Errors");
        }
        ...
}

ErrorsController.cs:

public class ErrorsController : Controller
{
    private readonly ILogger<ErrorController> _logger;
    private readonly IHostingEnvironment _environment;
    private readonly IHttpContextAccessor _httpContext;
    private readonly JiraSettings _jiraSettings;

    public ErrorController(
        ILogger<ErrorController> logger,
        IHostingEnvironment environment,
        IHttpContextAccessor httpContext)
    {
        _logger = logger;
        _environment = environment;
        _httpContext = httpContext;
    }

    [HttpGet]
    public IActionResult Get()
    {
        var exception = HttpContext.Features.Get<IExceptionHandlerFeature>();
        if (exception?.Error == null)
        {
            return NoContent();
        }

        var errorMessage = $"An error occurred while processing your request {exception.Error.GetErrorId()}";
        if (_environment.IsProduction() || _environment.IsStaging())
        {
            return Json(errorMessage);
        }

        errorMessage += $"\n{exception.Error.StackTrace}";
        return Json(errorMessage);
    }

神奇之处在于IExceptionHandlerFeature,可让您访问原始异常对象。如您所见,当我们执行有角度的应用程序时,JavaScript将错误输出为字符串,其中javascript接收错误消息字符串。您可以改为创建视图模型并返回视图。我们不在生产或暂存环境中显示异常信息。 GetErrorId()是我们编写的扩展方法,它获得异常的唯一ID。错误ID既显示给用户,也记录在日志中(在其他地方)。

相关问题