[英]error handling aspnet core 2.2 razor pages
I have a very simple exception that is handled by the default error page generated by VS2017 for razor pages .net core. 我有一个非常简单的异常,该异常由VS2017为剃刀页面.net核心生成的默认错误页面处理。 The error page shows with a exception error - is there any way I can show a custom error something like "Error in command try again" 错误页面显示异常错误-有什么办法可以显示自定义错误,例如“命令错误重试”
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);
}
Error page model 错误页面模型
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
Startup class I have added 我添加的启动类
app.UseExceptionHandler("/Error");
The ExceptionHandlerMiddleware
is designed to intercept unhandled exceptions. ExceptionHandlerMiddleware
旨在拦截未处理的异常。 You are handling your exception, but then throwing another, creating an new unhandled exception and thereby forcing the configured error page to be shown by the middleware. 您正在处理您的异常,但随后引发了另一个异常,从而创建了一个新的未处理的异常,从而迫使中间件显示已配置的错误页面。 I would add a public string property to the page in which the error happens, and set that to whatever error message you want in the catch
block, thereby handling the exception and not invoking the custom error page: 我将在发生错误的页面上添加一个公共字符串属性,并将其设置为您想要在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";
}
}
}
Add <p>@Model.ErrorMessage</p>
somewhere on the content page that belongs to the PageModel where this exception is raised. 在属于该异常的PageModel的内容页面上的某处添加<p>@Model.ErrorMessage</p>
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.