diff --git a/src/DigitalData.UserManager.API/Middleware/ExceptionHandlingMiddleware.cs b/src/DigitalData.UserManager.API/Middleware/ExceptionHandlingMiddleware.cs new file mode 100644 index 0000000..01096ef --- /dev/null +++ b/src/DigitalData.UserManager.API/Middleware/ExceptionHandlingMiddleware.cs @@ -0,0 +1,84 @@ +using DigitalData.Core.Exceptions; +using System.Net; +using System.Text.Json; + +namespace DigitalData.UserManager.API.Middleware; + +//TODO: Fix and use DigitalData.Core.Exceptions.Middleware +/// +/// Middleware for handling exceptions globally in the application. +/// Captures exceptions thrown during the request pipeline execution, +/// logs them, and returns an appropriate HTTP response with a JSON error message. +/// +[Obsolete("Use DigitalData.Core.Exceptions.Middleware")] +public class ExceptionHandlingMiddleware +{ + private readonly RequestDelegate _next; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The next middleware in the request pipeline. + /// The logger instance for logging exceptions. + public ExceptionHandlingMiddleware(RequestDelegate next, ILogger logger) + { + _next = next; + _logger = logger; + } + + /// + /// Invokes the middleware to handle the HTTP request. + /// + /// The HTTP context of the current request. + /// A task that represents the asynchronous operation. + public async Task InvokeAsync(HttpContext context) + { + try + { + await _next(context); // Continue down the pipeline + } + catch (Exception ex) + { + await HandleExceptionAsync(context, ex, _logger); + } + } + + /// + /// Handles exceptions by logging them and writing an appropriate JSON response. + /// + /// The HTTP context of the current request. + /// The exception that occurred. + /// The logger instance for logging the exception. + /// A task that represents the asynchronous operation. + private static async Task HandleExceptionAsync(HttpContext context, Exception exception, ILogger logger) + { + context.Response.ContentType = "application/json"; + + string message; + + switch (exception) + { + case BadRequestException badRequestEx: + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; + message = badRequestEx.Message; + break; + + case NotFoundException notFoundEx: + context.Response.StatusCode = (int)HttpStatusCode.NotFound; + message = notFoundEx.Message; + break; + + default: + logger.LogError(exception, "Unhandled exception occurred."); + context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; + message = "An unexpected error occurred."; + break; + } + + await context.Response.WriteAsync(JsonSerializer.Serialize(new + { + message + })); + } +} diff --git a/src/DigitalData.UserManager.API/Program.cs b/src/DigitalData.UserManager.API/Program.cs index 89b013d..9a2a4f2 100644 --- a/src/DigitalData.UserManager.API/Program.cs +++ b/src/DigitalData.UserManager.API/Program.cs @@ -1,23 +1,24 @@ -using Microsoft.EntityFrameworkCore; -using DigitalData.UserManager.Application; -using DigitalData.Core.Application; -using NLog.Web; -using NLog; -using DigitalData.Core.API; -using DigitalData.UserManager.API.Controllers; -using DigitalData.UserManager.Application.Services; -using Microsoft.Data.SqlClient; -using Newtonsoft.Json; -using Microsoft.IdentityModel.Tokens; -using DigitalData.UserManager.Application.DTOs.User; -using DigitalData.UserManager.API.Models; using DigitalData.Auth.Client; -using DigitalData.UserManager.API; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.Extensions.Options; using DigitalData.Core.Abstractions.Security.Extensions; -using Microsoft.OpenApi.Models; +using DigitalData.Core.API; +using DigitalData.Core.Application; +using DigitalData.UserManager.API; +using DigitalData.UserManager.API.Controllers; +using DigitalData.UserManager.API.Middleware; +using DigitalData.UserManager.API.Models; +using DigitalData.UserManager.Application; +using DigitalData.UserManager.Application.DTOs.User; +using DigitalData.UserManager.Application.Services; using DigitalData.UserManager.DependencyInjection; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.Data.SqlClient; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using Microsoft.OpenApi.Models; +using Newtonsoft.Json; +using NLog; +using NLog.Web; var logger = LogManager.Setup().LoadConfigurationFromAppSettings().GetCurrentClassLogger(); logger.Debug("init main"); @@ -170,6 +171,8 @@ try { return dCnnStr; }); + app.UseMiddleware(); + app.UseCors("DefaultCorsPolicy"); if (builder.Configuration.GetValue("UseSwagger"))