繁体   English   中英

不使用 try catch 的异常日志记录 - ASP.NET WEB API

[英]Exception Logging Without using try catch - ASP.NET WEB API

我需要在我的 API 中记录异常和错误请求。 目前我正在使用 try catch 来捕获异常并将其添加到我的日志中的 catch 块中。 这是正确的方法吗? 我阅读了 ASP.NET 中的全局错误处理。 我如何为这种情况实施这种方法?

下面是我的 API 控制器示例:

[HttpPost]
[Authorize]
[ValidateModel]
[Route("CheckProgramOwner")]
public async Task<IHttpActionResult> CheckProgramOwner([FromBody] CheckProgramOwner _data)
{
    try
    {              
        using (var db = new VisualVoiceFlowEntities())
        {
            var Result= await db.VVF_ScriptFlow.Where(s => s.ProgramId == _data.ProgramId).OrderByDescending(s => s.ID).FirstOrDefaultAsync();
            if(Result== null)
            {
                Log.Error("Error in CheckProgramOwner POST Request - " + "ProgramId not found");
                return Content(HttpStatusCode.BadRequest, "ProgramId not found");
            }
            string CurrentOwner = Result.ReadBy.ToString();
            return Ok(CurrentOwner);
        }
    }
    catch (Exception ex)
    {

        Log.Error("Error in CheckProgramOwner POST Request - " + ex.Message, ex);
        NewRelic.Api.Agent.NewRelic.NoticeError("Error in CheckProgramOwner POST Request - " + ex.Message, null);
        return Content(HttpStatusCode.InternalServerError, "Internal Server Error. Please Contact Admin.");
    }
}

如果您阅读 Casey 之前发布的文档,您将找到指向以下文档的链接,该文档解释了如何全局实现和注册异常过滤器:

https://docs.microsoft.com/en-us/aspnet/web-api/overview/error-handling/exception-handling#registering_exception_filters

然后,您可以在过滤器的主体中实现您的日志逻辑,从而避免在每次尝试/捕获时重复记录错误。 我建议使用您的原始方法记录更明显的错误,并使用过滤器记录任何其他错误(您可能没有想到。)

我使用 ExceptionFilter 做到了。 我创建了如下异常过滤器类 -


public class MyExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext context)
        {
            log4net.ThreadContext.Properties["addr"] = HttpContext.Current.Request.UserHostAddress;
            log4net.ThreadContext.Properties["Hostname"] = Dns.GetHostName().ToString();
            log4net.ThreadContext.Properties["PCName"] = Dns.GetHostAddresses(Environment.MachineName)[0].ToString();
            string RequestMethod = context.Request.Method.Method;
            dynamic ControllerInfo = context.ActionContext.ControllerContext.Controller;
            string RequestName = ControllerInfo.Url.Request.RequestUri.LocalPath.ToString().Replace("/api/", "").Replace("/VVFAPI", "");
            Log.Error("Error in " + RequestName +" "+ RequestMethod+ " Request - " + context.Exception.Message, context.Exception);
            NewRelic.Api.Agent.NewRelic.NoticeError("Error in " + RequestName + " " + RequestMethod + " Request - " + context.Exception.Message, null);
            HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("Internal Server Error. Please Contact Admin."),
                ReasonPhrase = "Critical Exception."
            };
            context.Response = msg;
        }
    }

另外,我相应地更改了我的控制器


        [HttpPost]
        [Authorize]
        [ValidateModel]
        [MyExceptionFilter]
        [Route("CheckProgramOwner")]
        public async Task<IHttpActionResult> CheckProgramOwner([FromBody] CheckProgramOwner _data)
        {
            Log.Info("CheckProgramOwner POST Request");
            using (var db = new VisualVoiceFlowEntities())
            {
                var Result = await db.VVF_ScriptFlow.Where(s => s.ProgramId == _data.ProgramId).OrderByDescending(s => s.ID).FirstOrDefaultAsync();
                if (Result == null)
                {
                    Log.Error("Error in CheckProgramOwner POST Request - " + "ProgramId not found");
                    return Content(HttpStatusCode.BadRequest, "ProgramId not found");
                }
                string CurrentOwner = Result.ReadBy.ToString();
                return Ok(CurrentOwner);
            }
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM