我有一个非常简单的异常,由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");
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";
}
}
}
在内容页面上的某处添加<p>@Model.ErrorMessage</p>
,该页面属于引发此异常的PageModel。