สร้างโฟลเดอร์ใหม่ชื่อ CustomExceptionMiddleware และ classExceptionMiddleware.cs ข้างใน
สิ่งแรกที่เราต้องทำคือลงทะเบียนบริการ IloggerManager และRequestDelegate ผ่านการแทรกการพึ่งพา
พารามิเตอร์ _next ของประเภท RequestDeleagate เป็นฟังก์ชันผู้รับมอบสิทธิ์ที่สามารถประมวลผลคำขอ HTTP ของเราได้
หลังจากขั้นตอนการลงทะเบียน เราจำเป็นต้องสร้างเมธอด InvokeAsync()RequestDelegate ไม่สามารถดำเนินการตามคำขอได้หากไม่มีมัน
ผู้รับมอบสิทธิ์ _next ควรดำเนินการตามคำขอและรับการดำเนินการจากผู้ควบคุมของเราควรสร้างการตอบสนองที่ประสบความสำเร็จ แต่ถ้าคำขอไม่สำเร็จ (และเป็นเพราะเราบังคับให้มีการยกเว้น)
มิดเดิลแวร์ของเราจะทริกเกอร์บล็อก catch และเรียก HandleExceptionAsyncmethod
public class ExceptionMiddleware{
private readonly RequestDelegate _next;
private readonly ILoggerManager _logger;
public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){
_logger = logger;
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext){
try{
await _next(httpContext);
}
catch (Exception ex){
_logger.LogError($"Something went wrong: {ex}");
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception){
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
return context.Response.WriteAsync(new ErrorDetails(){
StatusCode = context.Response.StatusCode,
Message = "Internal Server Error from the custom middleware."
}.ToString());
}
} แก้ไขคลาส ExceptionMiddlewareExtensions ของเราด้วยวิธีสแตติกอื่น -
public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder
app){
app.UseMiddleware<ExceptionMiddleware>();
} ใช้วิธีนี้ในวิธีกำหนดค่าในคลาสเริ่มต้น -
app.ConfigureCustomExceptionMiddleware();