перенаправить на страницу ошибки, когда возникла исключительная ситуация в asp.net? - PullRequest
0 голосов
/ 18 апреля 2011

Я хочу перенаправить на страницу ошибки при возникновении исключения.

Если код не обрабатывает try{}catch(Exception ex){} на странице и произошла ошибка в веб-приложении. Затем я хочу перенаправить Error.aspx с подробной информацией об исключении.

Я уже написал код на странице Global.asax, как это.

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    ' Code that runs when an unhandled error occurs
    Dim str As String = CType(sender, HttpApplication).Context.Request.Url.ToString
    Helper.ApplicationErrorHandler()
End Sub

Public Shared Sub ApplicationErrorHandler()
    Dim ex As Exception

    ex = HttpContext.Current.Server.GetLastError

    Dim str As String = HttpContext.Current.Request.Url.ToString()

    ' filter out 404 responses 
    Dim httpException = TryCast(ex, HttpException)
    If httpException IsNot Nothing AndAlso httpException.GetHttpCode() = 404 Then
        Return
    End If


    If TypeOf ex Is HttpUnhandledException AndAlso ex.InnerException IsNot Nothing Then
        ex = ex.InnerException
    End If

    If (ex IsNot Nothing) Then

        Dim msg As String = String.Format("An unhandled exception occurred:{0}Message: {1}{0}{0} Stack Trace:{0}{2}", System.Environment.NewLine, ex.Message, ex.StackTrace)
        Utility.SendEMail("LaborDB@alixpartners.com", System.Configuration.ConfigurationManager.AppSettings("ErrorEmailRecipient"), msg, "Labor Error")

    End If
    HttpContext.Current.Session.Add("Error", ex.Message)
    HttpContext.Current.Server.Transfer("error.aspx")

End Sub

Тем не менее это остановка исключения только на месте ошибки. он не перенаправляет на страницу ошибки.

    Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.  

Stack Trace: 


[NullReferenceException: Object reference not set to an instance of an object.]
   Labor.AttributeProcess.Page_Load(Object sender, EventArgs e) in C:\Source Trunk\Labor\Labor\AttributeProcess.aspx.vb:23
   System.Web.UI.Control.OnLoad(EventArgs e) +131
   System.Web.UI.Control.LoadRecursive() +65
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2427

Как справиться с этим? Я хочу перенаправить на страницу ошибки, когда возникла исключительная ситуация даже без попытки ... поймать дескриптор.

Ответы [ 2 ]

2 голосов
/ 18 апреля 2011

Проверьте элемент customErrors в web.config. Вы можете использовать его для настройки вашего веб-сайта для перенаправления на другие страницы при возникновении исключений.

0 голосов
/ 06 августа 2014

Ссылка, предложенная Jakob Gade , больше не работает, поэтому вот ответ, если у кого-то снова возникла такая же проблема, как у меня, скопируйте следующий код в метод Application_Error внутри global.asax:

// After Handle the error. Clear It
Server.ClearError();

// Clear rendered. Just if needed
Response.Clear();

// Finally redirect, transfer
Response.Redirect("~/ErrorViewer.aspx");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...