This commit is contained in:
s426226 2020-12-16 16:26:13 +01:00
parent 3e8eed3e25
commit 11f96f9d06
2 changed files with 42 additions and 1 deletions

View File

@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace Serwer.Api.Framework
{
public class ExceptionHandlerMiddleware
{
private readonly RequestDelegate _next;
public ExceptionHandlerMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
var statusCode = HttpStatusCode.BadRequest;
context.Response.StatusCode = (int)statusCode;
return context.Response.WriteAsync($"Error: {exception.Message}");
}
}
}

View File

@ -15,6 +15,7 @@ using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.IdentityModel.Tokens; using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Models;
using Serwer.Api.Framework;
using Serwer.Core.Repositories; using Serwer.Core.Repositories;
using Serwer.Infrastructure.Mappers; using Serwer.Infrastructure.Mappers;
using Serwer.Infrastructure.Repositories; using Serwer.Infrastructure.Repositories;
@ -88,6 +89,8 @@ namespace Serwer.Api
} }
app.UseRouting(); app.UseRouting();
app.UseMiddleware(typeof(ExceptionHandlerMiddleware));
app.UseAuthentication(); app.UseAuthentication();
app.UseAuthorization(); app.UseAuthorization();