使用 ExceptionHandler 中间件向客户端发送自定义 JSON 错误
定义代表你的自定义错误的类。
public class ErrorDto
{
public int Code { get; set; }
public string Message { get; set; }
// other fields
public override string ToString()
{
return JsonConvert.SerializeObject(this);
}
}
然后将下一个 ExceptionHandler 中间件放到 Configure 方法中。注意中间件顺序很重要。
app.UseExceptionHandler(errorApp =>
{
errorApp.Run(async context =>
{
context.Response.StatusCode = 500; // or another Status
context.Response.ContentType = "application/json";
var error = context.Features.Get<IExceptionHandlerFeature>();
if (error != null)
{
var ex = error.Error;
await context.Response.WriteAsync(new ErrorDto()
{
Code = <your custom code based on Exception Type>,
Message = ex.Message // or your custom message
... // other custom data
}.ToString(), Encoding.UTF8);
}
});
});