using BMA.EHR.Domain.Common; using BMA.EHR.Domain.Shared; using System.Net; namespace BMA.EHR.MetaData.Service { 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 { await _next(context); var response = context.Response; response.ContentType = "application/json"; var responseModel = new ResponseObject(); responseModel.Status = response.StatusCode; if (responseModel.Status == (int)HttpStatusCode.Unauthorized) { responseModel.Message = GlobalMessages.NotAuthorized; await response.WriteAsJsonAsync(responseModel); } if (responseModel.Status == (int)HttpStatusCode.Forbidden) { 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) { msg += $" {inner.Message}\r\n"; inner = inner.InnerException; } responseModel.Result = msg; switch (response.StatusCode) { case (int)HttpStatusCode.Unauthorized: responseModel.Message = GlobalMessages.NotAuthorized; break; case (int)HttpStatusCode.Forbidden: responseModel.Message = GlobalMessages.ForbiddenAccess; break; default: responseModel.Status = (int)HttpStatusCode.InternalServerError; responseModel.Message = GlobalMessages.ExceptionOccured; break; } await response.WriteAsJsonAsync(responseModel); } } #endregion } }