43 lines
1.1 KiB
C#
43 lines
1.1 KiB
C#
using Microsoft.AspNetCore.Mvc;
|
|
using MikrocopApi.Exceptions;
|
|
|
|
namespace MikrocopApi.Middleware;
|
|
|
|
public sealed class ExceptionHandlingMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public ExceptionHandlingMiddleware(RequestDelegate next)
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (AppException ex)
|
|
{
|
|
context.Response.StatusCode = ex.StatusCode;
|
|
await context.Response.WriteAsJsonAsync(new ProblemDetails
|
|
{
|
|
Title = ex.Title,
|
|
Detail = ex.Message,
|
|
Status = ex.StatusCode
|
|
});
|
|
}
|
|
catch (Exception)
|
|
{
|
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
await context.Response.WriteAsJsonAsync(new ProblemDetails
|
|
{
|
|
Title = "Internal Server Error",
|
|
Detail = "An unexpected error occurred.",
|
|
Status = StatusCodes.Status500InternalServerError
|
|
});
|
|
}
|
|
}
|
|
}
|