【问题标题】:error handling aspnet core 2.2 razor pages错误处理 aspnet core 2.2 razor pages
【发布时间】:2019-07-27 10:09:36
【问题描述】:

我有一个非常简单的异常,由 VS2017 为 razor pages .net core 生成的默认错误页面处理。 错误页面显示异常错误 - 有什么方法可以显示自定义错误,例如“命令中的错误重试”

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

【问题讨论】:

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


    【解决方案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>

    【讨论】:

    • 感谢非常有用 - 有没有办法实现这一点,所以我不必到处都有 try/catch?
    猜你喜欢
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 2020-11-21
    • 1970-01-01
    • 2018-10-29
    • 2021-07-27
    • 2019-10-06
    • 1970-01-01
    相关资源
    最近更新 更多