2
我试图在web api中实现全局异常日志记录,并发送frienldy消息给用户使用该错误ID,所以他可以回到我们的错误ID,所以我们可以修复它。我采取两种:ASP.NET Web API 2:ExceptionLogger和异常处理程序
- 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传递给异常处理程序以发送最终用户相应的错误ID的最佳方式是什么?