aspnet core 2.2刀片页面错误处理

时间:2019-03-05 20:48:28

标签: c# razor error-handling middleware razor-pages

我有一个非常简单的异常,该异常由VS2017为剃刀页面.net核心生成的默认错误页面处理。 错误页面显示异常错误-有什么办法可以显示自定义错误,例如“命令错误再次输入”

     try
      {

      var interenet = "nc -w 5 -z 8.8.8.8 53  >/dev/null 2>&1 && echo 'ok' || echo 'error'".Bash();

        }
        catch (Exception ex2)
           {
               _logger.LogError(
                            0, ex2,
                            "An exception was thrown attempting " +
                            "to execute the error handler.");

                    throw new Exception(ex2.Message);
   }

错误页面模型

public class ErrorModel : PageModel
    {
        public string RequestId { get; set; }

        public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);

        public void OnGet()
        {
            RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
        }
    }

我添加的启动类

   app.UseExceptionHandler("/Error");

1 个答案:

答案 0 :(得分:1)

ExceptionHandlerMiddleware旨在拦截未处理异常。您正在处理您的异常,但随后引发了另一个异常,从而创建了一个新的未处理的异常,从而迫使中间件显示已配置的错误页面。我将在发生错误的页面上添加一个公共字符串属性,并将其设置为您在catch块中所需的任何错误消息,从而处理异常而不调用自定义错误页面:

public class YourPageModel : PageModel
{
    public string ErrorMessage { get; set; }

    public void OnGet() // or OnPost, whichever
    {
        try
        {
            var internet = "nc -w 5 -z 8.8.8.8 53  >/dev/null 2>&1 && echo 'ok' || echo 'error'".Bash();
        }
        catch (Exception ex2)
        {
            _logger.LogError(0, ex2, "An exception was thrown attempting " +
                            "to execute the error handler.");
            ErrorMessage = "Error in command try again";
        }
    }
}

在内容页面上属于引发此异常的PageModel的某处添加<p>@Model.ErrorMessage</p>