Poszukiwacz/Serwer/Serwer.Api/Framework/ExceptionHandlerMiddleware.cs

39 lines
983 B
C#
Raw Permalink Normal View History

2020-12-16 16:26:13 +01:00
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}");
}
}
}