improve ErrorExceptionMiddleWare Code

This commit is contained in:
Suphonchai Phoonsawat 2025-04-25 10:23:47 +07:00
parent b90a0ad489
commit db483ce18d
2 changed files with 43 additions and 51 deletions

View file

@ -7,23 +7,13 @@ namespace BMA.EHR.Domain.Middlewares
{ {
public class ErrorHandlerMiddleware public class ErrorHandlerMiddleware
{ {
#region " Fields "
private readonly RequestDelegate _next; private readonly RequestDelegate _next;
#endregion
#region " Constructor and Destructor "
public ErrorHandlerMiddleware(RequestDelegate next) public ErrorHandlerMiddleware(RequestDelegate next)
{ {
_next = next; _next = next;
} }
#endregion
#region " Methods "
public async Task Invoke(HttpContext context) public async Task Invoke(HttpContext context)
{ {
try try
@ -31,58 +21,57 @@ namespace BMA.EHR.Domain.Middlewares
await _next(context); await _next(context);
var response = context.Response; var response = context.Response;
var statusCode = response.StatusCode;
var responseModel = new ResponseObject(); if (!response.HasStarted &&
responseModel.Status = response.StatusCode; (statusCode == (int)HttpStatusCode.Unauthorized || statusCode == (int)HttpStatusCode.Forbidden))
{
var responseModel = new ResponseObject
{
Status = statusCode,
Message = statusCode == (int)HttpStatusCode.Unauthorized
? GlobalMessages.NotAuthorized
: GlobalMessages.ForbiddenAccess
};
if (responseModel.Status == (int)HttpStatusCode.Unauthorized)
{
response.ContentType = "application/json"; response.ContentType = "application/json";
responseModel.Message = GlobalMessages.NotAuthorized;
await response.WriteAsJsonAsync(responseModel);
}
if (responseModel.Status == (int)HttpStatusCode.Forbidden)
{
response.ContentType = "application/json";
responseModel.Message = GlobalMessages.ForbiddenAccess;
await response.WriteAsJsonAsync(responseModel); await response.WriteAsJsonAsync(responseModel);
} }
} }
catch (Exception error) catch (Exception error)
{ {
var response = context.Response; var response = context.Response;
response.ContentType = "application/json";
var responseModel = new ResponseObject(); if (!response.HasStarted)
responseModel.Status = response.StatusCode;
var msg = error.Message;
var inner = error.InnerException;
while (inner != null)
{ {
msg += $" {inner.Message}\r\n"; response.Clear();
inner = inner.InnerException; response.ContentType = "application/json";
} response.StatusCode = (int)HttpStatusCode.InternalServerError;
responseModel.Result = msg;
switch (response.StatusCode) var msg = error.Message;
{ var inner = error.InnerException;
case (int)HttpStatusCode.Unauthorized: while (inner != null)
responseModel.Message = GlobalMessages.NotAuthorized; {
break; msg += $" {inner.Message}\r\n";
case (int)HttpStatusCode.Forbidden: inner = inner.InnerException;
responseModel.Message = GlobalMessages.ForbiddenAccess; }
break;
default: var responseModel = new ResponseObject
response.StatusCode = (int)HttpStatusCode.InternalServerError; {
responseModel.Status = (int)HttpStatusCode.InternalServerError; Status = response.StatusCode,
responseModel.Message = GlobalMessages.ExceptionOccured; Message = GlobalMessages.ExceptionOccured,
break; Result = msg
};
await response.WriteAsJsonAsync(responseModel);
}
else
{
// logging กรณีที่ response เริ่มถูกส่งแล้ว
Console.WriteLine("Cannot write error response, stream already started.");
Console.WriteLine(error);
} }
await response.WriteAsJsonAsync(responseModel);
} }
} }
#endregion
} }
} }

View file

@ -15,11 +15,14 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
//"DefaultConnection": "User Id=sys;Password=P@ssw0rd;DBA Privilege=SYSDBA;Data Source=localhost:1521/ORCLCDB", "LeaveConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms_leave;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"DefaultConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;" "MongoConnection": "mongodb://admin:adminVM123@192.168.1.80:27017",
"DefaultConnection": "server=192.168.1.80;user=root;password=adminVM123;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"RecruitConnection": "server=192.168.1.80;user=root;password=adminVM123;database=hrms_recruit;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;",
"ExamConnection": "server=192.168.1.80;user=root;password=adminVM123;database=hrms_exam;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
}, },
"Jwt": { "Jwt": {
"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI", "Key": "Hp3234M8rH1KjIdvhlUStayo6vIUOIeI76NKyIsiXJ8",
"Issuer": "https://id.frappet.synology.me/realms/hrms" "Issuer": "https://id.frappet.synology.me/realms/hrms"
}, },
"EPPlus": { "EPPlus": {