session-companion/SessionCompanion/SessionCompanion/Configurations/ExceptionMiddleware.cs

45 lines
1.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SessionCompanion.ViewModels.ApiResponses;
namespace SessionCompanion.Configurations
{
using System.Net;
using Microsoft.AspNetCore.Http;
using SessionCompanion.Extensions.ApiErrors;
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
public ExceptionMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task InvokeAsync(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
await HandleExceptionAsync(httpContext, ex);
}
}
private Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
string response = "{\"statusCode\":" + context.Response.StatusCode + ",\"message\":\"" + exception.Message
+ "\"}";
return context.Response.WriteAsync(response);
}
}
}