使用 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);
}
});
});