From 98e17766b203734a1817eed94338e2d25f4395f7 Mon Sep 17 00:00:00 2001 From: transtrike Date: Sat, 13 Feb 2021 16:20:18 +0200 Subject: Project Restructure P.1 --- .../DevHive.Web/Middleware/ExceptionMiddleware.cs | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs (limited to 'src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs') diff --git a/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs new file mode 100644 index 0000000..cb6d4ca --- /dev/null +++ b/src/Web/DevHive.Web/Middleware/ExceptionMiddleware.cs @@ -0,0 +1,50 @@ +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; + +namespace DevHive.Web.Middleware +{ + public class ExceptionMiddleware + { + private readonly RequestDelegate _next; + // private readonly ILogger _logger; + + public ExceptionMiddleware(RequestDelegate next) + { + this._next = next; + // this._logger = logger; + } + // public ExceptionMiddleware(RequestDelegate next, ILogger logger) + // { + // this._logger = logger; + // this._next = next; + // } + + public async Task InvokeAsync(HttpContext httpContext) + { + try + { + await this._next(httpContext); + } + catch (Exception ex) + { + // this._logger.LogError($"Something went wrong: {ex}"); + await HandleExceptionAsync(httpContext, ex); + } + } + + private Task HandleExceptionAsync(HttpContext context, Exception exception) + { + context.Response.ContentType = "application/json"; + context.Response.StatusCode = (int)HttpStatusCode.BadRequest; + + return context.Response.WriteAsync(new + { + StatusCode = context.Response.StatusCode, + Message = exception.Message + }.ToString()); + } + } +} -- cgit v1.2.3