Problem passing ELMAH log id to Custom Error page in ASP.NET

一个人想着一个人 提交于 2019-11-29 04:38:51

This works for me:

void ErrorLog_Logged(object sender, ErrorLoggedEventArgs args)
{
    if (args.Entry.Error.Exception is HandledElmahException)
        return;

    var config = WebConfigurationManager.OpenWebConfiguration("~");
    var customErrorsSection = (CustomErrorsSection)config.GetSection("system.web/customErrors");        

    if (customErrorsSection != null)
    {
        switch (customErrorsSection.Mode)
        {
            case CustomErrorsMode.Off:
                break;
            case CustomErrorsMode.On:
                FriendlyErrorTransfer(args.Entry.Id, customErrorsSection.DefaultRedirect);
                break;
            case CustomErrorsMode.RemoteOnly:
                if (!HttpContext.Current.Request.IsLocal)
                    FriendlyErrorTransfer(args.Entry.Id, customErrorsSection.DefaultRedirect);
                break;
            default:
                break;
        }
    }        
}

void FriendlyErrorTransfer(string emlahId, string url)
{
    Server.Transfer(String.Format("{0}?id={1}", url, Server.UrlEncode(emlahId)));
}

Unable to comment on Ronnie's solution. I had that in place for a while but it breaks the standard error flow process and causes ErrorLog_Logged to always transfer, even when calling

Elmah.ErrorSignal.FromCurrentContext().Raise(ex);

This is a problem if you still want to log an error from within a catch statement, for instance you have a workaround for an error but want to log the error to perform a proper fix, which can be pretty helpful on difficult to replicate issues.

I was able to correct this by using the following change:

//if (customErrorsSection != null)    
if (customErrorsSection != null && this.Context.Error != null)

This respects the typical error handling properly, as the context.Error will be null in cases where you explicitely raise the exception in Elmah, but is not null when falling through default error handling (not via a catch or if caught and re-thrown). This causes Ronnie's solution to respond similar to the .Net error handling logic.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!