我已将Serilog添加到我的项目中:
Program.cs
.UseSerilog((provider,context,loggerConfiguration) =>
{
loggerConfiguration
.MinimumLevel.Verbose()
.MinimumLevel.Override("microsoft",LogEventLevel.Warning);
.WriteTo.MSSqlServer(output,tableName: "Log",schemaName: "WPS")
.Enrich.WithAspnetcoreHttpcontext(provider)
.Enrich.WithExceptionDetails();
});
我还添加了一项服务,用于处理返回到UI的API错误:
Startup.cs
// Add Error Handling to all API endpoints
services.AddMvc(options => {
options.Filters.Add(new ApiExceptionFilter());
});
ApiExceptionFilter.cs
public class ApiExceptionFilter : ExceptionFilterAttribute
{
public override void OnException(ExceptionContext context)
{
ApiError apiError = null;
if (context.Exception is ApiException)
{
var ex = context.Exception as ApiException;
context.Exception = null;
apiError = new ApiError(ex.Message);
apiError.Errors = ex.Errors;
context.HttpContext.Response.StatusCode = ex.StatusCode;
}
else if (context.Exception is UnauthorizedaccessException)
{
apiError = new ApiError("Unauthorized access");
context.HttpContext.Response.StatusCode = 403;
}
else
{
string msg = context.Exception.GetBaseException().Message;
#if !DEBUG
string stack = "";
#else
string stack = context.Exception.StackTrace;
#endif
apiError = new ApiError(msg);
apiError.Detail = stack;
context.HttpContext.Response.StatusCode = 500;
}
context.Result = new JsonResult(apiError);
base.OnException(context);
}
}
但是,在添加ApiExceptionFilter之后,不再记录异常。
我已经尝试过再次引发该异常,但是自定义消息不再返回到UI。
ApiExceptionFilter.cs
base.OnException(context);
throw context.Exception.GetBaseException(); // throw again?
关于我要去哪里的任何建议吗?