ASP.net catch error on error page - c#

I have set up my custom error page which work fine:
<customErrors mode="On" redirectMode="ResponseRewrite">
<error statusCode="500" redirect="~/Pages/ErrorPages/500.aspx" />
</customErrors>
On 500.aspx:
Response.ClearContent();
Response.StatusCode = 500;
Exception = Server.GetLastError();
Code.Errors.Error.RecordNewError(ErrorType.InternalException, Exception, Code.Common.GetUserIPAddress().ToString(), HttpContext.Current);
Server.ClearError();
Problem is, if the error page throws an error itself we get an ugly error:
Runtime Error
Description: An exception occurred while processing your request.
Additionally, another exception occurred while executing the custom
error page for the first exception. The request has been terminated.
How do I fall back to a more basic custom error page if the error page itself throws an error?

Figured it out just now! Use the Page_Error method on the error pages themselves:
private void Page_Error(object sender, EventArgs e)
{
Response.ClearContent();
Response.StatusCode = 500;
Exception = Server.GetLastError();
HttpContext.Current.Response.Write("Error");
HttpContext.Current.Response.End();
}

Related

Elmah Raise() records inner exception

I'm trying to raise an exception using Elmah like this:
try
{
Foo();
}
catch (WebException ex)
{
var nex = new Exception("Foo failed", ex);
Elmah.ErrorSignal.FromCurrentContext().Raise(nex);
}
However, what Elmah records is the inner exception ex, not my new wrapper exception nex, i.e. the resulting database record has:
Type = "System.Net.WebException", Message = "The remote server returned an error: (400) Bad Request."
rather than, as I would expect:
Type = "System.Exception", Message = "Foo failed"
What on earth's going on?
ELMAH shows the type of the inner exception on the list of exceptions (/elmah.axd). If you click the Details link next to the error message, I'm pretty sure you'll see something like this:
System.Exception: Foo failed ---> System.Net.WebException
I just created a test project and verified that this is the experienced behaviour.
Edit: As discussed in comments, use of the base exception in the Type and Message fields appears to be the intended behavior.

How can i detect error from code behind to create a custom error page without using web.config? [duplicate]

This question already has answers here:
How to return 'own' 404 custom page?
(8 answers)
Closed 4 years ago.
I'm trying to detect error 404 and display a custom error page when it occurs using code behind in asp.net and not web.config. the code is not working, it just gives the default error page.
this is my code:
Exception exception = Server.GetLastError();
HttpException httpException = (HttpException)exception;
Server.ClearError();
if (httpException.ErrorCode == 404)
{
Response.Redirect("Page_Not_Found.aspx");
}
Better approach will be to handle it through web.confng like following.
<customErrors mode="On" defaultRedirect="~/UnexpectedError.html">
<error redirect="~/404Error.html" statusCode="404" />
</customErrors>

Creating Application_Error handler in Global.asax file getting a Parser Error

I am trying to add the Application_Error method into the Global.asax file, but I am getting a parser error:
Server Error in '/' Application. Parser Error Description: An error
occurred during the parsing of a resource required to service this
request. Please review the following specific parse error details and
modify your source file appropriately.
Parser Error Message: The content in the application file is not
valid.
I do not understand why it this method is not working. Any help is appreciated thanks!
<%#Application Language='C#' Inherits="Sitecore.Web.Application" %>
using System.Configuration;
protection void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Redirect HTTP errors to HttpError page
Server.Transfer("HttpErrorPage.aspx");
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write(
"<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}
I think that you should add the code in the .cs file.
Moreover protection is not accepted. Your code should be like this:
void Application_Error(object sender, EventArgs e)
{
//DoSomething();
}

Catch Error with Custome Error Page

I'm defining a custom Error page in ASP.NET
<customErrors mode="RemoteOnly" defaultRedirect="Oops.aspx"></customErrors>
When an Error occurs, I'm being redirect to that page with the following URL:
Oops.aspx?aspxerrorpath=/WebForm1.aspx
In the Page Load method of the Oops.aspx page, I'm trying to catch the error:
Exception exc = Server.GetLastError();
if (exc != null)
{
//do something
}
However, it seems that exc is actually null because none of the actions defined in that condition statement are being executed.
If you are logging the error in a datastore, the best way you can achieve this is by logging that error in Application_Error method of Global.asax, and then redirect to the Oops.aspx?refId=yourerrorId with the key of the error record that was stored in the datastore.

Good idea to catch HttpException?

I have the following error in my output.aspx page sometimes:
Exception Details: System.Web.HttpException: Request timed out.
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:
[HttpException (0x80004005): Request timed out.]
Is it a good idea to catch this exception? Where do I do that as my output.aspx.cs has a Page_Load and that function calls RunTable(). Should I put a try catch block around that functions content?
catch exception at application level
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// Get the exception object.
Exception exc = Server.GetLastError();
// Handle HTTP errors
if (exc.GetType() == typeof(HttpException))
{
// The Complete Error Handling Example generates
// some errors using URLs with "NoCatch" in them;
// ignore these here to simulate what would happen
// if a global.asax handler were not implemented.
if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength"))
return;
//Redirect HTTP errors to HttpError page
Server.Transfer("HttpErrorPage.aspx");
}
// For other kinds of errors give the user some information
// but stay on the default page
Response.Write("<h2>Global Page Error</h2>\n");
Response.Write(
"<p>" + exc.Message + "</p>\n");
Response.Write("Return to the <a href='Default.aspx'>" +
"Default Page</a>\n");
// Log the exception and notify system operators
ExceptionUtility.LogException(exc, "DefaultPage");
ExceptionUtility.NotifySystemOps(exc);
// Clear the error from the server
Server.ClearError();
}

Categories