ErrorsController

master
Tudor Stanciu 2022-01-18 14:17:50 +02:00
parent c3ef2abb55
commit ef3d9c74e0
2 changed files with 31 additions and 8 deletions

View File

@ -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<IExceptionHandlerFeature>();
var exception = context.Error;
return exception switch
{
ValidationException => StatusCode(StatusCodes.Status404NotFound, new { exception.Message }),
UnauthorizedAccessException => StatusCode(StatusCodes.Status401Unauthorized, new { exception.Message }),
_ => StatusCode(StatusCodes.Status500InternalServerError),
};
}
}
}

View File

@ -75,15 +75,10 @@ namespace NetworkResurrector.Api
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{ {
// global cors policy // global cors policy
app.UseCors(x => x app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
.AllowAnyOrigin() app.UseExceptionHandler("/error");
.AllowAnyMethod()
.AllowAnyHeader());
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting(); app.UseRouting();
app.UseAuthentication(); app.UseAuthentication();