Created
October 6, 2025 10:30
-
-
Save uzbekdev1/1b0a4aee29c80f0f68b800b2aad559e5 to your computer and use it in GitHub Desktop.
error handling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class GlobalMiddleware | |
| { | |
| private readonly RequestDelegate _next; | |
| private readonly ILogger<GlobalMiddleware> _logger; | |
| public GlobalMiddleware(RequestDelegate next,ILogger<GlobalMiddleware> logger) | |
| { | |
| _next = next; | |
| _logger = logger; | |
| } | |
| public async Task Invoke(HttpContext context) | |
| { | |
| try | |
| { | |
| await _next(context); | |
| } | |
| catch (Exception exception) | |
| { | |
| if (context.Response.HasStarted) | |
| { | |
| throw; | |
| } | |
| var message = exception.InnerException?.Message ?? exception.Message; | |
| _logger.LogError(message); | |
| var error = new ApiResponse | |
| { | |
| Data = null, | |
| Error = message, | |
| Success = false, | |
| Code = StatusCodes.Status500InternalServerError | |
| }; | |
| context.Response.StatusCode = StatusCodes.Status200OK; | |
| context.Response.ContentType = "application/json"; | |
| await context.Response.WriteAsync(error.ToString()); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment