diff options
| author | Jake Mannens <jake@asger.xyz> | 2026-06-05 00:37:02 +1000 |
|---|---|---|
| committer | Jake Mannens <jake@asger.xyz> | 2026-06-11 01:13:31 +1000 |
| commit | 81a0570c1b64891f286ee86d34d6f77090d525e3 (patch) | |
| tree | 1c98593ddec2eb64029f4fabe024cb5323050bb1 /ExceptionMiddleware.cs | |
| parent | 03055cb1b262a2b9a0516ad3aa523e503edeb36b (diff) | |
Deleted server-specific files
Diffstat (limited to 'ExceptionMiddleware.cs')
| -rw-r--r-- | ExceptionMiddleware.cs | 64 |
1 files changed, 0 insertions, 64 deletions
diff --git a/ExceptionMiddleware.cs b/ExceptionMiddleware.cs deleted file mode 100644 index ba4049a..0000000 --- a/ExceptionMiddleware.cs +++ /dev/null @@ -1,64 +0,0 @@ -using HyperBooru.ApiModels; -using System.Reflection; -using System.Text.Json; -using System.Text.Json.Serialization; -using System.Text.Json.Serialization.Metadata; - -namespace HyperBooru; - -// Middleware class to intercept API controller exceptions and -// return said exceptions to API clients as serialized JSON objects -public sealed class ExceptionMiddleware { - private RequestDelegate next; - - public ExceptionMiddleware(RequestDelegate next) => - this.next = next; - - public async Task Invoke(HttpContext context) { - try { - await next(context); - } catch(HBException e) { - context.Response.ContentType = "application/json"; - context.Response.StatusCode = - e.GetType().GetCustomAttribute<ExceptionStatusCodeAttribute>()?.StatusCode ?? - StatusCodes.Status500InternalServerError; - - context.Response.Clear(); - - await context.Response.WriteAsJsonAsync(e); - } catch(Exception) { - context.Response.StatusCode = StatusCodes.Status500InternalServerError; - context.Response.ContentType = "application/json"; - - context.Response.Clear(); - - await context.Response.WriteAsJsonAsync(new ServerException()); - } - } -} - -// This class is needed as the JSON serializer often fails to serialize -// members of the native 'Exception' class -public sealed class ExceptionJsonResolver : DefaultJsonTypeInfoResolver { - public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) { - var info = base.GetTypeInfo(type, options); - - if(!typeof(Exception).IsAssignableFrom(type)) - return info; - - string[] excludedProps = [ - "data", - "hResult", - "helpLink", - "innerException", - "source", - "stackTrace", - "targetSite" - ]; - - foreach(var p in info.Properties.Where(p => excludedProps.Contains(p.Name))) - p.ShouldSerialize = (_, _) => false; - - return info; - } -} |
