我一直在嘗試在我的 ASP.Net Core Web API 中使用自定義中間件設定全域例外處理。我需要使用Serilog將它們記錄到日志檔案中。我嘗試了很多,但我無法讓它作業。希望這里的朋友可以幫幫我。
我的自定義中間件:
public class ExceptionHandlingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionHandlingMiddleware> logger;
public ExceptionHandlingMiddleware()
{
}
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger)
{
_next = next ?? throw new ArgumentNullException(nameof(next));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
public async Task InvokeAsync(HttpContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
try
{
await _next.Invoke(context);
}
catch (Exception ex)
{
await HandleExceptionAsync(context, ex);
}
}
private async Task HandleExceptionAsync(
HttpContext context,
Exception exception)
{
try
{
int statusCode = 0;
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (exception is null)
{
throw new ArgumentNullException(nameof(exception));
}
this.logger.LogError(exception.ToString());
CustomApiResponse<CustomApiErrorResponse> errorResponse = null;
if (exception is MyException myExceptionInfo)
{
statusCode = myExceptionInfo.StatusCode == default ? (int)HttpStatusCode.InternalServerError : myExceptionInfo.StatusCode;
errorResponse = new CustomApiResponse<CustomApiErrorResponse>()
{
StatusCode = statusCode,
TraceId = context.TraceIdentifier,
Response = new CustomApiErrorResponse()
{
Message = myExceptionInfo.ErrorMessage,
StackTrace = myExceptionInfo.StackTrace
}
};
}
else
{
statusCode = (int)HttpStatusCode.InternalServerError;
const string message = "Unexpected error";
errorResponse = new CustomApiResponse<CustomApiErrorResponse>()
{
StatusCode = (int)HttpStatusCode.InternalServerError,
Response = new CustomApiErrorResponse()
{
Message = message,
},
TraceId = context.TraceIdentifier
};
}
var responseContent = JsonConvert.SerializeObject(errorResponse);
context.Response.ContentType = "application/json";
context.Response.StatusCode = statusCode;
await context.Response.WriteAsync(responseContent);
}
catch (Exception ex)
{
this.logger.LogError(ex.ToString());
throw;
}
}
}
啟動檔案
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
//app.UseExceptionHandlerMiddleware();
app.UseExceptionHandler(new ExceptionHandlerOptions
{
ExceptionHandler = new ExceptionHandlingMiddleware().InvokeAsync,
});
//app.UseExceptionHandler(options =>
//{
// options.Run(async context =>
// {
// // Exception Handling Code
// });
//}
}
我哪里錯了?我還需要做些什么才能讓它作業嗎?例外會從代碼中拋出,但不會被中間件捕獲。請幫助我的朋友。
更新
我正在使用 GraphQL 而不是 REST。所以我的應用程式中沒有控制器。這是這個問題的原因嗎?
uj5u.com熱心網友回復:
嘗試像這樣改變你的啟動:
app.UseMiddleware<ExceptionHandlingMiddleware>();
代替
app.UseExceptionHandler(new ExceptionHandlerOptions
{
ExceptionHandler = new ExceptionHandlingMiddleware().InvokeAsync,
});
uj5u.com熱心網友回復:
本文將幫助您學習如何操作:https : //www.c-sharpcorner.com/article/implement-global-exception-handling-in-asp-net-core-application/
uj5u.com熱心網友回復:
確保您ExceptionHandlingMiddleware.cs在Middleware檔案夾中。
并在您的配置方法中使用以下內容:-
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<ExceptionHandlingMiddleware>();
...
它將解決您的問題。如果仍然無效,請告訴我。
uj5u.com熱心網友回復:
首先感謝大家抽出時間幫助我。我在示例 REST API 專案中嘗試了相同的中間件和例外,并且作業正常。所以我得出結論,中間件不起作用,因為我的實際專案使用 GraphQL 而不是 REST。現在我需要弄清楚為什么它不起作用以及如何使它起作用。所以再次感謝大家。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362694.html
