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

78 lines
2.6 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;
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-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";
2023-06-25 18:48:28 +07:00
await response.WriteAsJsonAsync(responseModel);
}
}
catch (Exception error)
{
var response = context.Response;
2025-04-25 10:23:47 +07:00
if (!response.HasStarted)
2023-06-25 18:48:28 +07:00
{
2025-04-25 10:23:47 +07:00
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;
}
2023-06-25 18:48:28 +07:00
2025-04-25 10:23:47 +07:00
var responseModel = new ResponseObject
{
Status = response.StatusCode,
Message = GlobalMessages.ExceptionOccured,
Result = msg
};
await response.WriteAsJsonAsync(responseModel);
}
else
2023-06-25 18:48:28 +07:00
{
2025-04-25 10:23:47 +07:00
// logging กรณีที่ response เริ่มถูกส่งแล้ว
Console.WriteLine("Cannot write error response, stream already started.");
Console.WriteLine(error);
2023-06-25 18:48:28 +07:00
}
}
}
}
}