创建一个自定义异常处理程序中间件,根据客户端请求生成响应
create a Custom Exception Handler Middleware generating response based on client request
如何创建自定义异常处理程序中间件。此中间件应根据调用客户端生成自定义响应。如果客户端通过 AJAX 请求,则响应应该是描述错误的 JSON 响应,否则将客户端重定向到错误页面。
控制器代码
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
中间件代码
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
var customError = new CustomError();
switch (error)
{
case AppException e:
// custom application error
customError.StatusCode = (int)HttpStatusCode.BadRequest;
break;
case KeyNotFoundException e:
// not found error
customError.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
customError.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
customError.ErrorMessage = error?.Message;
if (context.Request.ContentType == "application/json;")
{
var result = JsonSerializer.Serialize(customError);
await response.WriteAsync(result);
}
else
{
context.Response.Redirect("/Errors/CustomError");
}
}
}
自定义错误class代码
public class CustomError
{
public int StatusCode { get; set; }
public string ErrorMessage { get; set; }
}
错误视图模型
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
您可以在启动时添加代码 class:
app.UseStatusCodePagesWithReExecute("/errors/{0}");
添加一个控制器(在我的例子中,我用 HttpContext.Request.Headers["Content-Type"] 进行了测试,它应该是 context.Request.ContentType == "application/json;" 对于 MVC项目):
public class ErrorsController : Controller
{
[Route("errors/{statusCode}")]
public IActionResult CustomError(int statusCode)
{
if (HttpContext.Request.Headers["Content-Type"] == "application/json")
{
var cuserr = new CustomError() { ErrorMessage = "err", StatusCode = statusCode };
return new JsonResult(cuserr);
}
else
{
if (statusCode == 404)
{
return View("~/Views/Errors/404.cshtml");
}
return View("~/Views/Errors/500.cshtml");
}
}
}
和观点:
结果:
更多细节,您可以阅读官方文档:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0
如何创建自定义异常处理程序中间件。此中间件应根据调用客户端生成自定义响应。如果客户端通过 AJAX 请求,则响应应该是描述错误的 JSON 响应,否则将客户端重定向到错误页面。
控制器代码
public IActionResult Index()
{
return View();
}
public IActionResult Privacy()
{
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
中间件代码
public class ErrorHandlerMiddleware
{
private readonly RequestDelegate _next;
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception error)
{
var response = context.Response;
var customError = new CustomError();
switch (error)
{
case AppException e:
// custom application error
customError.StatusCode = (int)HttpStatusCode.BadRequest;
break;
case KeyNotFoundException e:
// not found error
customError.StatusCode = (int)HttpStatusCode.NotFound;
break;
default:
// unhandled error
customError.StatusCode = (int)HttpStatusCode.InternalServerError;
break;
}
customError.ErrorMessage = error?.Message;
if (context.Request.ContentType == "application/json;")
{
var result = JsonSerializer.Serialize(customError);
await response.WriteAsync(result);
}
else
{
context.Response.Redirect("/Errors/CustomError");
}
}
}
自定义错误class代码
public class CustomError
{
public int StatusCode { get; set; }
public string ErrorMessage { get; set; }
}
错误视图模型
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
您可以在启动时添加代码 class:
app.UseStatusCodePagesWithReExecute("/errors/{0}");
添加一个控制器(在我的例子中,我用 HttpContext.Request.Headers["Content-Type"] 进行了测试,它应该是 context.Request.ContentType == "application/json;" 对于 MVC项目):
public class ErrorsController : Controller
{
[Route("errors/{statusCode}")]
public IActionResult CustomError(int statusCode)
{
if (HttpContext.Request.Headers["Content-Type"] == "application/json")
{
var cuserr = new CustomError() { ErrorMessage = "err", StatusCode = statusCode };
return new JsonResult(cuserr);
}
else
{
if (statusCode == 404)
{
return View("~/Views/Errors/404.cshtml");
}
return View("~/Views/Errors/500.cshtml");
}
}
}
和观点:
结果:
更多细节,您可以阅读官方文档: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-6.0