using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Shared; using Microsoft.AspNetCore.Http; using System.Net; namespace BMA.EHR.Domain.Middlewares { public class ErrorHandlerMiddleware { private readonly RequestDelegate _next; public ErrorHandlerMiddleware(RequestDelegate next) { _next = next; } public async Task Invoke(HttpContext context) { try { await _next(context); var response = context.Response; var statusCode = response.StatusCode; if (!response.HasStarted && (statusCode == (int)HttpStatusCode.Unauthorized || statusCode == (int)HttpStatusCode.Forbidden)) { var responseModel = new ResponseObject { Status = statusCode, Message = statusCode == (int)HttpStatusCode.Unauthorized ? GlobalMessages.NotAuthorized : GlobalMessages.ForbiddenAccess }; response.ContentType = "application/json"; await response.WriteAsJsonAsync(responseModel); } } catch (Exception error) { var response = context.Response; if (!response.HasStarted) { response.Clear(); response.ContentType = "application/json"; response.StatusCode = (int)HttpStatusCode.InternalServerError; var msg = error.Message; var inner = error.InnerException; while (inner != null) { msg += $" {inner.Message}\r\n"; inner = inner.InnerException; } var responseModel = new ResponseObject { Status = response.StatusCode, Message = GlobalMessages.ExceptionOccured, Result = msg }; await response.WriteAsJsonAsync(responseModel); } else { // logging กรณีที่ response เริ่มถูกส่งแล้ว Console.WriteLine("Cannot write error response, stream already started."); Console.WriteLine(error); } } } } }