72 lines
1.9 KiB
C#
72 lines
1.9 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace Library;
|
|
|
|
public class ExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
|
|
public ExceptionMiddleware( RequestDelegate next )
|
|
{
|
|
_next = next;
|
|
}
|
|
|
|
public async Task InvokeAsync( HttpContext httpContext )
|
|
{
|
|
try
|
|
{
|
|
await _next( httpContext );
|
|
}
|
|
catch ( RedirectException exception )
|
|
{
|
|
HandleExceptionAsync( httpContext , exception );
|
|
}
|
|
catch ( ErrorException exception )
|
|
{
|
|
await HandleErrorAsync( httpContext , exception );
|
|
}
|
|
catch ( APIErrorException exception )
|
|
{
|
|
await HandleApiErrorAsync( httpContext , exception );
|
|
}
|
|
catch ( Exception exception )
|
|
{
|
|
await HandleExceptionAsync( httpContext , exception );
|
|
}
|
|
}
|
|
|
|
private void HandleExceptionAsync( HttpContext context , RedirectException exception )
|
|
{
|
|
context.Response.Redirect( exception.Destination );
|
|
}
|
|
|
|
private static Task HandleErrorAsync( HttpContext context , ErrorException exception )
|
|
{
|
|
context.Response.StatusCode = 500;
|
|
return context.Response.WriteAsync( exception.ErrorMessage );
|
|
}
|
|
private static Task HandleApiErrorAsync( HttpContext context , APIErrorException exception )
|
|
{
|
|
using MemoryStream stream = new( );
|
|
|
|
using Utf8JsonWriter writer = new( stream );
|
|
writer.WriteStartObject( );
|
|
writer.WriteBoolean( "Success" , false );
|
|
writer.WriteString( "ErrorMessage" , exception.ErrorMessage );
|
|
writer.WriteEndObject( );
|
|
writer.Dispose( );
|
|
|
|
context.Response.ContentType = System.Net.Mime.MediaTypeNames.Application.Json;
|
|
return context.Response.WriteAsync( Encoding.UTF8.GetString( stream.ToArray( ) ) );
|
|
}
|
|
|
|
private static Task HandleExceptionAsync( HttpContext context , Exception exception )
|
|
{
|
|
context.Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Plain;
|
|
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
|
|
return context.Response.WriteAsync( exception.ToString( ) );
|
|
}
|
|
} |