From ef3d9c74e08dd5374e8d76d1564b918ad30e695c Mon Sep 17 00:00:00 2001 From: Tudor Stanciu Date: Tue, 18 Jan 2022 14:17:50 +0200 Subject: [PATCH] ErrorsController --- .../Controllers/ErrorsController.cs | 28 +++++++++++++++++++ src/api/NetworkResurrector.Api/Startup.cs | 11 ++------ 2 files changed, 31 insertions(+), 8 deletions(-) create mode 100644 src/api/NetworkResurrector.Api/Controllers/ErrorsController.cs diff --git a/src/api/NetworkResurrector.Api/Controllers/ErrorsController.cs b/src/api/NetworkResurrector.Api/Controllers/ErrorsController.cs new file mode 100644 index 0000000..b6109f7 --- /dev/null +++ b/src/api/NetworkResurrector.Api/Controllers/ErrorsController.cs @@ -0,0 +1,28 @@ +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Diagnostics; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using System; +using System.ComponentModel.DataAnnotations; + +namespace NetworkResurrector.Api.Controllers +{ + [AllowAnonymous] + [ApiExplorerSettings(IgnoreApi = true)] + public class ErrorsController : ControllerBase + { + [Route("error")] + public IActionResult HandleErrors() + { + var context = HttpContext.Features.Get(); + var exception = context.Error; + + return exception switch + { + ValidationException => StatusCode(StatusCodes.Status404NotFound, new { exception.Message }), + UnauthorizedAccessException => StatusCode(StatusCodes.Status401Unauthorized, new { exception.Message }), + _ => StatusCode(StatusCodes.Status500InternalServerError), + }; + } + } +} diff --git a/src/api/NetworkResurrector.Api/Startup.cs b/src/api/NetworkResurrector.Api/Startup.cs index c0b867f..f4378bd 100644 --- a/src/api/NetworkResurrector.Api/Startup.cs +++ b/src/api/NetworkResurrector.Api/Startup.cs @@ -75,15 +75,10 @@ namespace NetworkResurrector.Api public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // global cors policy - app.UseCors(x => x - .AllowAnyOrigin() - .AllowAnyMethod() - .AllowAnyHeader()); + app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()); + app.UseExceptionHandler("/error"); - if (env.IsDevelopment()) - { - app.UseDeveloperExceptionPage(); - } + app.UseRouting(); app.UseAuthentication();