Error handling

Errors can be handled at three different levels of the ASP.NET web application – app, page or code (class). To handle errors at the application level, the developer has two files at their command: global.asax and web.config.

At the page level, the developer can use the Page_Error event handler, and at the code level, developers can insert try... catch...finally blocks. These blocks are resource intensive, so they should be used carefully on critical code only, like database connections. Incorrect user input is so common that you shouldn’t be handled with catch blocks, but with if statements.

The Page_Error handler isn’t recommend to handle exceptions, and developers should turn to the Application_Error handler. It should also be remembered that you cannot access controls with the Page_Error, because it is called before any controls have been created.

The developer can decide whether to add handling instructions in global.asax and/or web.config with the appropriate .aspx pages to handle the exceptions. If you go with the global.asax file you will use the Application_Error method and to redirect users the Server.Transfer method is considered best practice compared to Response.Redirect, because the Server.Transfer will not create as much traffic. The Response.Redirect makes a call to the client asking the browser to make the request for a new page, while the Server.Transfer will automatically call the new page.

The global.asax code will resemble the following:

void Application_Error(object sender EventsArgs e) {
Server.Transfer("handleError.aspx");
}

In the .aspx page, you will have a Page_Error method similar to the following:

private void Page_Error {
Trace.Write("Error" + Server.GetLastError().Message);
Server.ClearError();
}

Trace.Write is the best option, because it will be seen only by the developer, as long as you are sure to have localOnly="true" in the web.config page.

HTTP errors directed at .aspx pages can also be handled with the web.config settings under <custom Errors>. Errors on web pages ending with .htm or text files will not benefit from this setting, because the IIS server will never turn over the handling of these pages to asp.net, so the customErrors settings will never be consulted.

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

No comments yet.

Leave a comment

(required)

(required)