62 lines
2.0 KiB
C#
62 lines
2.0 KiB
C#
using IM.Commons;
|
|
using IM.DomainCommons;
|
|
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace IM.ASPNETCore
|
|
{
|
|
public class ExceptionMiddleware
|
|
{
|
|
private readonly RequestDelegate _next;
|
|
private readonly ILogger<ExceptionMiddleware> logger;
|
|
|
|
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
|
|
{
|
|
_next = next;
|
|
this.logger = logger;
|
|
}
|
|
|
|
public async Task InvokeAsync(HttpContext context)
|
|
{
|
|
try
|
|
{
|
|
await _next(context);
|
|
}
|
|
catch (DomainException ex)
|
|
{
|
|
await DomainExceptionHandlerAsync(context, ex);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
await UnhandledExceptionHandlerAsync(context, ex);
|
|
}
|
|
}
|
|
|
|
public Task DomainExceptionHandlerAsync(HttpContext context, DomainException ex)
|
|
{
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = StatusCodes.Status400BadRequest;
|
|
var result = Result<object>.Fail(ResultCode.PARAMETER_ERROR, ex.Message);
|
|
return context.Response.WriteAsJsonAsync(result);
|
|
}
|
|
|
|
private Task UnhandledExceptionHandlerAsync(HttpContext context, Exception ex)
|
|
{
|
|
var correlationId = context.TraceIdentifier;
|
|
logger.LogError(ex,
|
|
"Unhandled exception. CorrelationId: {CorrelationId}, Path: {Path}",
|
|
correlationId,
|
|
context.Request.Path);
|
|
|
|
context.Response.ContentType = "application/json";
|
|
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
|
context.Response.Headers["X-Correlation-ID"] = correlationId;
|
|
|
|
var result = Result<object>.Fail(
|
|
ResultCode.SYSTEM_ERROR,
|
|
$"系统错误,关联编号:{correlationId}");
|
|
return context.Response.WriteAsJsonAsync(result);
|
|
}
|
|
}
|
|
}
|