private async Task HandleAsync(HttpContext context, Exception ex) { var responseStatusCode = HttpStatusCode.InternalServerError; var responseText = string.Empty; if (ex is ValidationException valdEx) { responseStatusCode = HttpStatusCode.BadRequest; responseText = JsonConvert.SerializeObject( new ValidationErrorResponseModel { Message = valdEx.Message, Data = valdEx.GetData() }, NewtonsoftLogic.GetCammelCaseSettings()); } else { var(statusCode, data) = ex switch { NotFoundException _ => (HttpStatusCode.NotFound, ex.GetData()), ApiVersionException _ => ((HttpStatusCode)ex.GetData()[ApiVersionException.StatusCode], ex.GetData()), IdentityException _ => (HttpStatusCode.Unauthorized, ex.GetData()), _ => (HttpStatusCode.InternalServerError, null) }; responseStatusCode = statusCode; responseText = JsonConvert.SerializeObject/*JsonSerializer.Serialize*/ ( new ErrorResponseModel <object> { Message = statusCode == HttpStatusCode.InternalServerError ? "Operation failed." : ex.Message, Data = data }, NewtonsoftLogic.GetCammelCaseSettings()); } context.Response.StatusCode = (int)responseStatusCode; context.Response.ContentType = "application/json"; await context.Response.WriteAsync(responseText); }
public async Task <TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate <TResponse> next) { var guid = Guid.NewGuid(); var requestName = $"{request.GetType().Name}_{guid}"; logger.LogInformation($"Handling request: {requestName}"); var responseName = $"{typeof(TResponse).Name}_{guid}"; TResponse response; try { response = await next(); } catch (Exception ex) { logger.LogError(ex, $"\nRequest: {requestName} \nResponse: {responseName} \nException: \n{JsonConvert.SerializeObject(ex, NewtonsoftLogic.GetCammelCaseSettings())/*JsonSerializer.Serialize(ex)*/}", null); throw ex; } finally { logger.LogInformation($"Handled request: {requestName}"); logger.LogInformation($"Handled response: {responseName}"); } return(response); }