ArticleDirectory
- Page Level
- Application Level
- Local error handling
- Page Level
- Application Level
- HTTP module level
- Prevent infinite Recursion
- Parser errors
- Exception logging and response time
Introduction
When errors occur in an ASP. NET application, they either get handled or propagates unhandled to higher scopes. when an unhandled exception propagates, the user may be redirected to an error page using different ASP. net configuration settings. however, such a redirection may be prevented in the first place by handling the exceptions that get thrown. error Handling in ASP. net therefore, may be divided into two separate Logics:
- Redirecting the user to an error page when errors go unhandled.
- Handling exceptions when they get thrown.
Redirecting the user to an error page
There are two different scopes where we cocould specify which page the user shocould be redirected to, when errors go unhandled:
- Page Level (applies to errors that happen within a single page ).
- Application level (applies to errors that happen anywhere in the application ).
Page Level
UseErrorpageAttribute in the webform.
This attribute defines the page the user shocould be redirected to when an unhandled exception occurs in that specific page. For example,
& Lt; % @ page Language = "C #" codebehind = "webform1.aspx. CS "autoeventwireup =" false "inherits =" webtest. webform1 "<strong> errorpage ="/webtest/errorpages/pageerror.html "</strong> % & gt; |
TheErrorpageAttribute maps toPage. errorpageProperty, and hence may be set programmatically. The value may optionally include query string parameters. If no parameters are added, ASP. NET wocould automatically add one with the nameAspxerrorpath. This parameter wocould hold the value of the relative URL to this page, so that the error page wocould be able to determine which page caused the error.
If a value is specified in this attribute (or property) and an unhandled exception occurs in the page,PageClass wowould automatically perform a redirect to the specified page. If a value is not specified, the exception is assumed to be unhandled, wrapped in a newHttpunhandledexceptionAnd then thrown, propagating it to the next higher level.
Application Level
UseCustomerrorsSection inWeb. config.
This section lets you specify the error page to which the user shocould be redirected to when an unhandled exception propagates in the application level. this section specifies error pages for both default errors as well as the HTTP status code errors.
& Lt;Customerrors mode = "on" defaultredirect = "/webtest/errorpages/apperror.html"& Gt;& Lt;Error statuscode = "404" Redirect = "/webtest/errorpages/404.html "/& Gt;& Lt;/Customerrors& Gt; |
TheModeAttribute specifies whether to show user-defined custom error pages or ASP. NET error pages. Three values are supported for this attribute:
Remoteonly-Custom error pages are shown for all remote users. ASP. NET error pages with rich error information are displayed only for local users.
On-Custom error pages are always shown, unless one is not specified. when a custom error page is not defined, an ASP. net error page will be displayed which describes how to enable remote viewing of errors.
Off-Custom error pages are not shown. Instead, ASP. NET error pages will be displayed always, which will have rich error information.
It's a bad idea to give users more information than what is required. ASP. NET error pages describe technical details that shouldn't be exposed. Ideally,ModeAttribute thus shocould not be setOff.
TheDefaultredirectAttribute specifies the path to a generic error page. This page wocould typically have a link to let the user go back to the home page or perform the request once again.
EachErrorElement defines a redirect specific to a participant HTTP Status Code. For example, if the error is a 404 (File not found), then you cocould set the error pageFilenotfound.htm. You cocould add as your error elements inCustomerrorsSection as required, each of which specifies a status code and the corresponding error page path. if ASP. net can't find any specific error element corresponding to a status code, it wocould use the value specified inDefaultredirectAttribute.
Notes
- the settings specified in the page level (
errorpage attribute) wocould override those specified in the customerrors section. the reason is because errors in the page wocould be handled by the page class first, which might thus prevent the exception from being propagated to the application level. it's only when the page class fails to handle the exception that the values set in customerrors come into scope.
- All these settings mentioned above apply only for requests that are made for ASP. net files. more specifically, these settings wocould work only for requests for files with extensions that are mapped to the aspnet_isapi. for example, if you request for an ASP or JPG file (extensions that are not mapped to aspnet_isapi) which does not exist, then these settings won't work, and the standard error page specified in IIS wocould be displayed. to modify this behavior, either map the required extensions to aspnet_isapi or modify the custom error pages specified in IIS.
Handling exceptions
There are different levels where you cocould handle exceptions.
- Locally (method level), where exceptions cocould be thrown.
- Page Level by handling
Page. ErrorEvent.
- Application level by handling
Httpapplication. ErrorEvent.
- HTTP module level by handling
Httpapplication. ErrorEvent.
Local error handling
Wrap code that might throw exceptions inTry-Catch-FinallyBlock.
If you can recover from the exception, then handle it inCatchBlock. if the exception cannot be recovered from locally, let the exception propagate to higher levels by throwing it. if the exception cannot be recovered from locally, but additional information can be provided, then wrap the exception with the new information and throw the new exception. this method is used when you use M quota tions. place the clean up code inFinallyBlock.
Find more information on Exception Handling best practices available in msdn.
Note: The more exceptions you catch and throw, the slower your application wocould run. This is more significant in Web applications.
Page Level
Attach a handler toPage. ErrorEvent. in C #, you will have to write the event wire up code yourself inPage_loadMethod.
When an exception goes unhandled in a page,ErrorEvent ofPageClass gets triggered.
Typically, the first action you wowould perform in this handler wocould be to obtain the exception thrown, by usingServer. getlasterrorMethod. This method wocould return a reference to the lastExceptionObject that was thrown.
After you getExceptionObject, you will want to redirect the user to an error page. We cocould Make ASP. NET do the redirection by usingErrorpageAttribute ofPage(Design time) or by usingPage. errorpageProperty (runtime). obviusly, the choice here wocould be to programmatically set the value usingPage. errorpageProperty in the event handler.
Private Void Webform1_error ( Object Sender, eventargs E)
{
// Get the last exception thrown
Exception ex = Server. getlasterror ();
// Do something with the exception like logging etc.
// Set the error page
This . Errorpage = " /Errorhandling/errorpages/baseerror.html " ;
}
If you do not specify an error page, the exception gets wrapped insideHttpunhandledexceptionObject and propagates. if you don't want the exception to be wrapped, then simply throw the last exception, which wowould force immediate propagation escaping any intervention. however, this wowould prevent ASP. net from redirecting the user to a page specific page either. in other words, if you are going to throw the last error (or any exception for that matter), setting the error page will have no effect.
Private Void Basepage_error ( Object Sender, eventargs E)
{
// Get the last exception thrown
Exception ex = Server. getlasterror ();
// Do something with the exception like logging etc.
// The statement below has no significance-it's as good as commented
This . Errorpage = " /Errorhandling/errorpages/baseerror.html " ;
// Throw the error to prevent wrapping
Throw Ex;
}
To reduce redundant code, you cocould define a base web form page which definesPage. ErrorEvent handler and then wire up code in the constructor, and then make all your web form pages derive from this base page. this wocould save you the effort of writing the error handler in each web form.
Application Level
Attach an event handler toApplication. ErrorEvent.
When an unhandled exception leaves a page, it gets propagated to the application level, which wowould trigger this event.
There are two things you wowould want to do in an application error handler.
- Get the last exception thrown using
Server. getlasterror.
- Clear the error using
Server. clearerror, To inform ASP. NET that you have handled the error.
If you don't clear the error, the exception wowould propagate. however, since there isn't any higher scope where the exception cocould be caught, Asp. net is forced to handle it. the way ASP. net handles the exception depends upon the settings specified inCustomerrorsSection we saw before. If no settings are defined, ASP. NET wocould use the defaults and display the infamous 'yellow' error page.
HTTP module level
Instead of handling application errors inGlobal. asax, Exceptions may also be handled by attaching an HTTP module which wowould have a handler attached toApplication. ErrorEvent. this method wocould be triggered before the corresponding application handler wocould be invoked. such an implementation wocould be beneficial if you have multiple projects with the same global error handling implementation. in such a scenario, you can create a module and attach it to each web application you have.
All the points we saw in the page and application handlers apply to the module handler as well.
Important notesprevent infinite Recursion
If an error occurs in the error handling code, an infinite recursive loop wowould result, which wowould soon drag your server down. the reason why this happens is because the new exception wocould trigger the error event once again which wocould in turn redirect control to the handler, which wocould cause yet another exception to be thrown, making an infinite loop.
This might also happen if the error page itself throws an exception. To counter this possibility, making error pages static is a good idea.
Errors may also happen while attempting to redirect to an error page usingServer. TransferOrResponse. RedirectMaybe due to an invalid path. To tackle this scenario, we cocould wrap the redirection code inTry-CatchBlock. If the redirection fails, then we have nothing more to do other than setting the response code and completing the response, usingResponse. statuscodeProperty andHttpapplication. completeresponseMethod. This wowould then be handled by the settings specified inCustomerrorsSection.
Parser errors
Parser errors are caused due to invalid tags (or similar reasons) In An ASPX page. These errors are usually of TypeHttpparseexception. Such errors will not be caught by the page level handler as page parsing happens before ASP. net creates the Assembly for the ASPX page. in other words, Parser errors are thrown while ASP. net reads the aspx file and tries to create its assembly, and hence is way before the corresponding type is created. thus, such errors will have to be handled in the application scope.
Exception logging and response time
users need to get responses as quick as possible. implementation wise, this means that when errors happen, error recovery processes shoshould be quick and users shoshould be redirected or informed of the error as soon as possible. if conditions are going to be logged to a file or other mediums, then it cocould take time which wowould lead to a slow response. making exception logging an asynchronous process wocould be a good idea in this respect.