![](/img/trans.png)
[英]How to write unit test for Program and Startup cs file for ASP.NET Core Web API app
[英]Globally capture the program exception error and write to a file in asp.net core 2.1 web api
我正在尝试为asp.net core 2.1 Web API中的执行错误而不是http状态错误创建全局异常处理服务,并写入文件。
尝试了一些选择,例如
services.AddMvc(config =>
{
config.Filters.Add(typeof(GlobalExceptionFilter));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddSessionStateTempDataProvider();
例外类别
public class GlobalExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
HttpStatusCode status = HttpStatusCode.InternalServerError;
String message = String.Empty;
var exceptionType = context.Exception.GetType();
if (exceptionType == typeof(UnauthorizedAccessException))
{
message = "Unauthorized Access";
status = HttpStatusCode.Unauthorized;
}
else if (exceptionType == typeof(NotImplementedException))
{
message = "A server error occurred.";
status = HttpStatusCode.NotImplemented;
}
else if (exceptionType == typeof(MyAppException))
{
message = context.Exception.ToString();
status = HttpStatusCode.InternalServerError;
}
else
{
message = context.Exception.Message;
status = HttpStatusCode.NotFound;
}
context.ExceptionHandled = true;
HttpResponse response = context.HttpContext.Response;
response.StatusCode = (int)status;
response.ContentType = "application/json";
var err = message + " " + context.Exception.StackTrace;
response.WriteAsync(err);
}
}
但是它从来没有出现错误。我尝试调试但从未触及调试代码。
任何人都可以让我如何记录文件中的全局错误。
从此解决方案中找到了一些解决方案https://blog.elmah.io/error-logging-middleware-in-aspnetcore/
https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/error-handling?view=aspnetcore-2.1
http://www.talkingdotnet.com/global-exception-handling-in-aspnet-core-webapi/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.