使用program.cs并在asp.net管道上添加中间件。
这是一个AdvanceExceptionHandler示例:
namespace AryaVtd.Orca.Server.Infrastructure.Middlewares.Logging
{
public class AdvancedExceptionHandler
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;
private readonly IWebHostEnvironment _env;
public AdvancedExceptionHandler(RequestDelegate next, ILoggerFactory logger, IWebHostEnvironment env)
{
_next = next;
_logger = logger.CreateLogger(typeof(AdvancedExceptionHandler).Name);
_env = env;
}
public async Task Invoke(HttpContext context)
{
string message = null;
HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError;
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError($"AryaVtd.Orca.Server.Infrastructure.Middlewares.Logging:\r\nSource: {ex.Source} \r\nMessage: {ex.GetMessages()}");
if (_env.IsDevelopment())
{
var dic = new Dictionary<string, string>
{
["StackTrace"] = ex.StackTrace,
["Exception"] = ex.Message
};
message = JsonConvert.SerializeObject(dic);
}
else
{
message = "AdvancedExceptionHandler: unfortunately an error has occurred on server!";
}
await WriteToReponseAsync();
}
async Task WriteToReponseAsync()
{
var exceptionResult = new ExceptionResult(message, (int)httpStatusCode);
var result = JsonConvert.SerializeObject(exceptionResult);
context.Response.StatusCode = (int)httpStatusCode;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(result);
}
}
}
public static class ExceptionHandlerMiddlewareExtension
{
public static void UseAdvancedExceptionHandler(this IApplicationBuilder app)
{
app.UseMiddleware<AdvancedExceptionHandler>();
}
}
}
呼叫应用程序。在program.cs的早期使用AdvancedExceptionHandler()。
app.UseAdvancedExceptionHandler();