将异常作为JSON消息返回
我正在使用ASP.NET Core开发API,并且正在努力处理异常.
I am developing an API with ASP.NET Core and I am struggling with the exception handling.
当发生任何异常时,或者在要返回具有不同状态代码的自定义错误的任何控制器中,我想返回JSON格式的异常报告.我在错误响应中不需要HTML.
When any exception occurs, or in any controller where I want to return custom errors with different status codes, I want to return JSON-formatted exception reports. I do not need an HTML in the error responses.
我不确定是否应该为此使用中间件.如何在ASP.NET Core API中返回JSON异常?
I'm not sure if I should use middleware for this, or something else. How should I return JSON exceptions in an ASP.NET Core API?
好,我有一个很满意的解决方案.
Ok, I got a working solution, that I am pretty happy with.
-
添加中间件: 在
Configure
方法中,注册中间件(ASP.NET Core附带).
Add middleware: In the
Configure
Method, register the middleware (comes with ASP.NET Core).
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// logging stuff, etc.
app.UseStatusCodePagesWithReExecute("/error/{0}");
app.UseExceptionHandler("/error");
app.UseMvc(); // if you are using Mvc
// probably other middleware stuff
}
为消息创建类 编写一个简单的类,表示要在任何错误情况下作为请求发送的 JSON错误消息的实例:
Create a Class for Messages Write a simple class that represents instances of JSON Error Messages you want to send as a request in any error case:
public class ExceptionMessageContent
{
public string Error { get; set; }
public string Message { get; set; }
}
创建错误控制器 添加用于处理所有预期和意外错误的 Error Controller .请注意,这些路由与中间件配置相对应.
Create Error Controller add the Error Controller that handles all expected and unexpected errors. Note, that these routes correspond to the middleware configuration.
[Route("[controller]")]
public class ErrorController : Controller
{
[HttpGet]
[Route("")]
public IActionResult ServerError()
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
var content = new ExceptionMessageContent()
{
Error = "Unexpected Server Error",
Message = feature?.Error.Message
};
return Content( JsonConvert.SerializeObject( content ), "application/json" );
}
[HttpGet]
[Route("{statusCode}")]
public IActionResult StatusCodeError(int statusCode)
{
var feature = this.HttpContext.Features.Get<IExceptionHandlerFeature>();
var content = new ExceptionMessageContent() { Error = "Server Error", Message = $"The Server responded with status code {statusCode}" };
return Content( JsonConvert.SerializeObject( content ), "application/json" );
}
}
现在,当我想在任何地方抛出错误时,我都可以这样做.该请求将重定向到错误处理程序,并发送带有精美格式错误消息的500
.同样,404
和其他代码也可以正常处理.我想发送的任何自定义状态代码,也可以用ExceptionMessageContent
的实例返回,例如:
Now, when I want to throw an error anywhere, I can just do that. The request gets redirected to the error handler and sends a 500
with a nice formatted error message. Also, 404
and other codes are handled gracefully. Any custom status codes I want to send, I can also return them with an instance of my ExceptionMessageContent
, for example:
// inside controller, returning IActionResult
var content = new ExceptionMessageContent() {
Error = "Bad Request",
Message = "Details of why this request is bad."
};
return BadRequest( content );