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
{
#region " Fields "
private readonly RequestDelegate _next;
#endregion
#region " Constructor and Destructor "
public ErrorHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
#endregion
#region " Methods "
public async Task Invoke(HttpContext context)
{
try
@ -31,58 +21,57 @@ namespace BMA.EHR.Domain.Middlewares
await _next(context);
var response = context.Response;
var statusCode = response.StatusCode;
var responseModel = new ResponseObject();
responseModel.Status = 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
};
if (responseModel.Status == (int)HttpStatusCode.Unauthorized)
{
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);
}
}
catch (Exception error)
{
var response = context.Response;
response.ContentType = "application/json";
var responseModel = new ResponseObject();
responseModel.Status = response.StatusCode;
var msg = error.Message;
var inner = error.InnerException;
while (inner != null)
if (!response.HasStarted)
{
msg += $" {inner.Message}\r\n";
inner = inner.InnerException;
}
responseModel.Result = msg;
response.Clear();
response.ContentType = "application/json";
response.StatusCode = (int)HttpStatusCode.InternalServerError;
switch (response.StatusCode)
{
case (int)HttpStatusCode.Unauthorized:
responseModel.Message = GlobalMessages.NotAuthorized;
break;
case (int)HttpStatusCode.Forbidden:
responseModel.Message = GlobalMessages.ForbiddenAccess;
break;
default:
response.StatusCode = (int)HttpStatusCode.InternalServerError;
responseModel.Status = (int)HttpStatusCode.InternalServerError;
responseModel.Message = GlobalMessages.ExceptionOccured;
break;
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);
}
await response.WriteAsJsonAsync(responseModel);
}
}
#endregion
}
}

View file

@ -15,11 +15,14 @@
},
"AllowedHosts": "*",
"ConnectionStrings": {
//"DefaultConnection": "User Id=sys;Password=P@ssw0rd;DBA Privilege=SYSDBA;Data Source=localhost:1521/ORCLCDB",
"DefaultConnection": "server=192.168.1.80;user=root;password=adminVM123;port=3306;database=hrms;Convert Zero Datetime=True;Allow User Variables=true;Pooling=True;"
"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;",
"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": {
"Key": "HP-FnQMUj9msHMSD3T9HtdEnphAKoCJLEl85CIqROFI",
"Key": "Hp3234M8rH1KjIdvhlUStayo6vIUOIeI76NKyIsiXJ8",
"Issuer": "https://id.frappet.synology.me/realms/hrms"
},
"EPPlus": {