ASP.NET Web API 2:ExceptionLogger和Exception Handler

时间:2016-09-23 14:29:03

标签: c# error-handling exception-handling asp.net-web-api2

我正在尝试在web api中实现全局异常日志记录,并使用该错误ID向用户发送frienldy消息,因此他可以回复给我们并提供错误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从异常记录器传递到异常处理程序以向最终用户发送相应的错误ID的最佳方法是什么?

1 个答案:

答案 0 :(得分:3)

您可以将其添加到<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.42/css/bootstrap-datetimepicker.css"> <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.42/js/bootstrap-datetimepicker.min.js"></script> <div class="container"> <div class="row"> <div class='col-sm-6'> <div class="form-group"> <div class='input-group date' id='appointment_end_datetime'> <input type='text' class="form-control" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> </div> </div>

HttpRequestMessage.Properties

然后在logger / handler中使用这些扩展方法:

public static class HttpRequestMessageExtensions
{
    private const string LogId = "LOG_ID";

    public static void SetLogId(this HttpRequestMessage request, Guid id)
    {
        request.Properties[LogId] = id;
    }

    public static Guid GetLogId(this HttpRequestMessage request)
    {
        object value;
        if (request.Properties.TryGetValue(LogId, out value))
        {
            return (Guid) value;
        }

        return Guid.Empty;
    }
}