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();