forked from xiongyuxing/tiku-backend.net
feat: add api security foundation
This commit is contained in:
33
Tiku.Api/Middleware/ExceptionHandlingMiddleware.cs
Normal file
33
Tiku.Api/Middleware/ExceptionHandlingMiddleware.cs
Normal file
@@ -0,0 +1,33 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
|
||||
namespace Tiku.Api.Middleware;
|
||||
|
||||
public sealed class ExceptionHandlingMiddleware(
|
||||
RequestDelegate next,
|
||||
ILogger<ExceptionHandlingMiddleware> logger,
|
||||
IHostEnvironment environment)
|
||||
{
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "Unhandled API exception");
|
||||
|
||||
var problem = new ProblemDetails
|
||||
{
|
||||
Title = "An unexpected error occurred.",
|
||||
Status = StatusCodes.Status500InternalServerError,
|
||||
Detail = environment.IsDevelopment() ? exception.Message : null,
|
||||
Instance = context.Request.Path
|
||||
};
|
||||
|
||||
problem.Extensions["traceId"] = context.TraceIdentifier;
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(problem);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user