hrms-api-backend/BMA.EHR.Domain/Middlewares/ErrorHandlerMiddleware.cs

181 lines
6.7 KiB
C#
Raw Normal View History

2023-06-25 18:48:28 +07:00
using BMA.EHR.Domain.Common;
using BMA.EHR.Domain.Shared;
2023-07-12 21:50:11 +07:00
using Microsoft.AspNetCore.Http;
2023-06-25 18:48:28 +07:00
using System.Net;
2025-06-23 17:03:18 +07:00
using System.Text.Json;
2023-06-25 18:48:28 +07:00
2023-07-12 21:50:11 +07:00
namespace BMA.EHR.Domain.Middlewares
2023-06-25 18:48:28 +07:00
{
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;
2025-04-25 10:23:47 +07:00
var statusCode = response.StatusCode;
2023-06-25 18:48:28 +07:00
2025-06-23 17:03:18 +07:00
// ตรวจสอบว่า response ยังไม่ถูกส่งและเป็น status code ที่ต้องการจัดการ
2025-04-25 10:23:47 +07:00
if (!response.HasStarted &&
(statusCode == (int)HttpStatusCode.Unauthorized || statusCode == (int)HttpStatusCode.Forbidden))
2023-06-25 18:48:28 +07:00
{
2025-04-25 10:23:47 +07:00
var responseModel = new ResponseObject
{
Status = statusCode,
Message = statusCode == (int)HttpStatusCode.Unauthorized
? GlobalMessages.NotAuthorized
: GlobalMessages.ForbiddenAccess
};
response.ContentType = "application/json";
2025-06-23 17:03:18 +07:00
// ใช้ JsonSerializer แทน WriteAsJsonAsync เพื่อความปลอดภัย
var jsonResponse = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(jsonResponse);
2023-06-25 18:48:28 +07:00
}
}
catch (Exception error)
{
2025-06-23 17:03:18 +07:00
await HandleExceptionAsync(context, error);
}
}
2023-06-25 18:48:28 +07:00
2025-06-23 17:03:18 +07:00
private static async Task HandleExceptionAsync(HttpContext context, Exception error)
{
var response = context.Response;
2025-04-25 10:23:47 +07:00
2025-06-23 17:03:18 +07:00
// ตรวจสอบว่า response ยังไม่ถูกส่งไป
if (response.HasStarted)
{
// ถ้า response เริ่มแล้ว ไม่สามารถแก้ไขได้ แค่ log
Console.WriteLine("Cannot write error response, stream already started.");
Console.WriteLine($"Error: {error}");
return;
}
2023-06-25 18:48:28 +07:00
2025-06-23 17:03:18 +07:00
try
{
// Clear response เฉพาะเมื่อยังไม่ได้เริ่มส่ง
response.Clear();
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
2025-04-25 10:23:47 +07:00
2025-06-23 17:03:18 +07:00
// สร้าง error message
var msg = error.Message;
var inner = error.InnerException;
while (inner != null)
2023-06-25 18:48:28 +07:00
{
2025-06-23 17:03:18 +07:00
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
2023-06-25 18:48:28 +07:00
}
2025-06-23 17:03:18 +07:00
var responseModel = new ResponseObject
{
Status = response.StatusCode,
Message = GlobalMessages.ExceptionOccured,
Result = msg
};
// ใช้ JsonSerializer และ WriteAsync เพื่อหลีกเลี่ยงปัญหา stream
var jsonResponse = JsonSerializer.Serialize(responseModel);
await response.WriteAsync(jsonResponse);
}
catch (Exception writeError)
{
// ถ้าเขียน response ไม่ได้ ให้ log error
Console.WriteLine("Failed to write error response:");
Console.WriteLine($"Original Error: {error}");
Console.WriteLine($"Write Error: {writeError}");
2023-06-25 18:48:28 +07:00
}
}
}
}
2025-06-23 17:03:18 +07:00
// 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);
// }
// }
// }
// }
// }