【发布时间】:2017-02-01 11:06:57
【问题描述】:
我正在尝试在 web api 中实现全局异常日志记录,并向具有该错误 ID 的用户发送一条友好的消息,以便他可以返回给我们错误 ID,以便我们修复它。我正在实现这两个:
- System.Web.Http.ExceptionHandling.ExceptionLogger
- System.Web.Http.ExceptionHandling.ExceptionHandler
这是我的覆盖 ExceptionLogger 抽象类的类:
public class GlobalExceptionLogger : System.Web.Http.ExceptionHandling.ExceptionLogger
{
public override void Log(ExceptionLoggerContext context)
{
LogMessage logMsg = new LogMessage();
logMsg.ID = System.Guid.NewGuid().ToString();
logMsg.MessageType = MessageType.ResourceServerAPI;
logMsg.SenderMethod = context.Request.RequestUri != null ? string.Format("Request URL: {0}", context.Request.RequestUri.ToString()) : "";
logMsg.Level = MesageLevel.Error;
logMsg.MachineName = Environment.MachineName;
logMsg.Message = context.Exception.Message;
Logger.LogError(logMsg);
}
}
这是我处理错误的方式:
public class GlobalExceptionHandler : System.Web.Http.ExceptionHandling.ExceptionHandler
{
public override void Handle(ExceptionHandlerContext context)
{
var metadata = new ErrorData
{
Message = "An error occurred! Please use the ticket ID to contact our support",
DateTime = DateTime.Now,
RequestUri = context.Request.RequestUri,
ErrorId = //get the ID already logged
};
var response = context.Request.CreateResponse(HttpStatusCode.InternalServerError, metadata);
context.Result = new ResponseMessageResult(response);
}
}
由于异常记录发生在处理之前,将 ID 从 Exception Logger 传递到 Exception Handler 以向最终用户发送相应的错误 Id 的最佳方法是什么?
【问题讨论】:
标签: c# error-handling exception-handling asp.net-web-api2