CustomExceptionMiddleware라는 새 폴더와 그 안에 classExceptionMiddleware.cs를 만듭니다.
가장 먼저 해야 할 일은 종속성 주입을 통해 IloggerManager 서비스와 RequestDelegate를 등록하는 것입니다.
RequestDeleagate 유형의 _next 매개변수는 HTTP 요청을 처리할 수 있는 함수 대리자입니다.
등록 프로세스 후에 InvokeAsync() 메서드를 생성해야 합니다. RequestDelegate는 그것 없이는 요청을 처리할 수 없습니다.
_next 대리자는 요청을 처리해야 하고 컨트롤러의 Get 작업은 성공적인 응답을 생성해야 합니다. 그러나 요청이 실패한 경우(그리고 예외를 강제 실행하기 때문에)
미들웨어는 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>();
} Startup 클래스의 Configure 메소드에서 이 메소드를 사용하십시오 -
app.ConfigureCustomExceptionMiddleware();