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的最佳方式是什麼?