簡體   English   中英

global.asax 中的 Application_Error 未捕獲 WebAPI 中的錯誤

[英]Application_Error in global.asax not catching errors in WebAPI

對於我正在從事的項目,我們正在實施的其中一項內容是我們在我的一些團隊較舊的 ASP.NET 和 MVC 項目中擁有代碼的內容 - Application_Error異常捕獲器,它向開發團隊發送一封電子郵件,其中包含異常經驗和最相關的細節。

這是它的外觀:

全球.asax:

protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    string path = "N/A";
    if (sender is HttpApplication)
        path = ((HttpApplication) sender).Request.Url.PathAndQuery;

    string args = string.Format("<b>Path:</b> {0}", path);

    // Custom code that generates an HTML-formatted exception dump
    string message = Email.GenerateExceptionMessage(ex, args);

    // Custom code that sends an email to the dev team.
    Email.SendUnexpectedErrorMessage("Some App", message);
}

但是,有一個“小”問題——當我故意讓一部分代碼拋出異常以測試這種機制時......

public static void GetMuffinsByTopping(string topping)
{
    throw new Exception("Test Exception!", new Exception("Test Inner Exception!!!"));

    // Actual repository code is unreachable while this test code is there
}

前端 JavaScript 立即攔截了一個 HTTP 500 請求,但是沒有到達上面提到的 global.asax.cs 代碼(我在方法的第一行執行了一個斷點。)

問題:如何讓“舊的” Application_Error處理程序發送錯誤電子郵件,以便我們團隊的開發人員可以更輕松地調試我們的應用程序?

將您的錯誤處理邏輯從Application_Error抽象為它自己的函數。 創建一個Web API 異常過濾器

//register your filter with Web API pipeline
//this belongs in the Application_Start event in Global Application Handler class (global.asax)
//or some other location that runs on startup
GlobalConfiguration.Configuration.Filters.Add(new LogExceptionFilterAttribute());

//Create filter
public class LogExceptionFilterAttribute : ExceptionFilterAttribute 
{
    public override void OnException(HttpActionExecutedContext context)
    {
        ErrorLogService.LogError(context.Exception);
    }
}

//in global.asax or global.asax.cs
protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    ErrorLogService.LogError(ex);
} 

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Email developers, call fire department, log to database etc.
    }
}

來自 Web API 的錯誤不會觸發 Application_Error 事件。 但是我們可以創建一個異常過濾器並注冊它來處理錯誤。 另請參閱ASP.NET Web API 2 中的全局錯誤處理

就我而言,我不喜歡使用 Web.config。 然后我在 Global.asax 文件中創建了上面的代碼:

protected void Application_Error(object sender, EventArgs e)
    {
        Exception ex = Server.GetLastError();

        //Not Found (When user digit unexisting url)
        if(ex is HttpException && ((HttpException)ex).GetHttpCode() == 404)
        {
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "NotFound");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
        else //Unhandled Errors from aplication
        {
            ErrorLogService.LogError(ex);
            HttpContextWrapper contextWrapper = new HttpContextWrapper(this.Context);

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");
            routeData.Values.Add("action", "Index");

            IController controller = new ErrorController();
            RequestContext requestContext = new RequestContext(contextWrapper, routeData);
            controller.Execute(requestContext);
            Response.End();
        }
    }

那是我的 ErrorController.cs

public class ErrorController : Controller
{
    // GET: Error
    public ViewResult Index()
    {
        Response.StatusCode = 500;
        Exception ex = Server.GetLastError();
        return View("~/Views/Shared/SAAS/Error.cshtml", ex);
    }

    public ViewResult NotFound()
    {
        Response.StatusCode = 404;
        return View("~/Views/Shared/SAAS/NotFound.cshtml");
    }
}

這是我從@mason 類復制的 ErrorLogService.cs

//common service to be used for logging errors
public static class ErrorLogService
{
    public static void LogError(Exception ex)
    {
        //Do what you want here, save log in database, send email to police station
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM