diff --git a/Api/Middleware/ExceptionHandlerMiddleware.cs b/Api/Middleware/ExceptionHandlerMiddleware.cs new file mode 100644 index 0000000000000000000000000000000000000000..0194c9626401c8108da6099004f29ef760aa79d4 --- /dev/null +++ b/Api/Middleware/ExceptionHandlerMiddleware.cs @@ -0,0 +1,29 @@ +using Microsoft.AspNetCore.Diagnostics; + +namespace Api.Middleware +{ + public class ExceptionHandlerMiddleware : IExceptionHandler + { + private readonly ILogger<ExceptionHandlerMiddleware> _logger; + + public ExceptionHandlerMiddleware(ILogger<ExceptionHandlerMiddleware> logger) + { + _logger = logger; + } + + public async ValueTask<bool> TryHandleAsync(HttpContext httpContext, Exception exception, CancellationToken cancellationToken) + { + httpContext.Response.StatusCode = 500; + httpContext.Response.ContentType = "application/json"; + _logger.LogInformation($"[{DateTimeOffset.Now}] {exception.GetType().Name} at ID {httpContext.TraceIdentifier}, Method {httpContext.Request.Method}: \"{exception.Message}\""); + + var error = new + { + StatusCode = 500, + Message = "The server encountered an unexpected error. Please try again later." + }; + await httpContext.Response.WriteAsJsonAsync(error, cancellationToken: cancellationToken); + return true; + } + } +} diff --git a/Api/Program.cs b/Api/Program.cs index fc2fd6ca6254b38f8a3c72a17d8be4dcd9cd915b..e5222e5602b770b877a7cae32aaa912debe1ecc0 100644 --- a/Api/Program.cs +++ b/Api/Program.cs @@ -1,3 +1,4 @@ +using Api.Middleware; using DAL.Data; using Microsoft.EntityFrameworkCore; @@ -10,6 +11,8 @@ IConfigurationRoot configuration = new ConfigurationBuilder() .AddJsonFile($"appsettings.{envName}.json", optional: true, reloadOnChange: true) .Build(); +builder.Services.AddLogging(); + // Add services to the container. builder.Services.AddDbContextFactory<RestaurantDBContext>(options => options.UseSqlServer(configuration.GetConnectionString("MSSQL")) @@ -20,6 +23,7 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); +builder.Services.AddExceptionHandler<ExceptionHandlerMiddleware>(); var app = builder.Build(); @@ -28,6 +32,11 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + app.UseDeveloperExceptionPage(); +} +else +{ + app.UseExceptionHandler("/Error"); } app.UseHttpsRedirection();