Stackify is now BMC. Read theBlog

How to Handle Application_error in ASP.NET App’s Global.asax

  |  April 22, 2024
How to Handle Application_error in ASP.NET App’s Global.asax

ASP.NET offers many benefits, such as improved security, easy updating, language independence and less overall code. With that said, .NET is not without errors and issues, even when working with a professional, such as this .NET development company. One common error is an Application_error in the Global.asax file. Let’s understand how to handle ASP.NET App’s Global.asax and other common errors in .NET.

What is Global.asax?

The Global.asax file is used to handle high level application events, such as:

  • Application start
  • Application error
  • Session start
  • Session end

Also known as ASP.NET Application File, this file is located within the root directory of a .NET application.

Within the file is a Class that represents the entire application. When run, Global.asax is parsed and compiled into a .NET Framework class. The file is configured so users cannot download the file or view the code within it.

The Global.asax file is optional. It’s only necessary if you want to handle sessions or application events, like the ones listed above.

Adding a Global.asax file is easy:

  1. Open Visual Studio
  2. Choose “Create a new website”
  3. Navigate to the Solution Explorer
  4. Choose “Add New Item”
  5. Select “Global Application Class”
  6. Choose “Add”

Although optional, the Global.asax file is helpful when creating ASP.NET projects because it allows you to handle events without having to add code to every page of the website.

How to Handle Application_error in ASP.NET App’s Global.asax

ASP.NET provides developers with an easy way to handle errors using the Global.asax and the easy-to-use Application_Error event. You can easily begin handling errors with the following code:

protected void Application_Error(Object sender, EventArgs e) {

//coding in here

}

When there’s an error, you can determine what to do inside the brackets above. For example, if you wanted the last error found, you can add in some of the following coding:

Exception ex = Server.GetLastError();

You can now use ex any time you want to log errors or perform an action based on the information inside of the exception. Let’s assume that you want to simply exit out of the error if there’s been a ThreadAboutException.

This would require just two additional lines of coding:

If (ex is ThreadAboutException)

return;

Your code would look something like this:

protected void Application_Error(Object sender, EventArgs e) {

Exception ex = Server.GetLastError();

If (ex is ThreadAboutException)

return;

}

The developer can choose to log the error and then redirect the user to an error page of your choosing.

Ode to Code has a lot of great examples on how you can amplify your error coding using this function. ASP.NET makes error handling easy and you can even handle the errors on page level for greater refinement.

ASP.NET Error Handling at Page Level

Microsoft’s documentation offers a robust example on how to handle errors on the page level. ASP.NET has a built-in handle, Page_Error, to help you understand the errors that happen on a page.

An example would be:

private void Page_Error(object sender, EventArgs e)

{

//coding goes here

}

This handler will catch all of the errors that aren’t already handled in your try/catch on the page. Inside of the coding above, where it says “coding goes here,” you’ll want to add in your error handling logic.

Typically, you’ll add in the following code to get the last error sent by the server:

    Exception exc = Server.GetLastError();

The “exc” allows you to handle exceptions using HttpUnhandledException. Let’s take a look at how you would handle your error in the next few lines of coding.

  if (exc is HttpUnhandledException)

    {

        ErrorMsgTextBox.Text = “message goes here”

    }

You only have one task left to do at this point: clear the error. It’s easy to clear the error using the following line of coding:

Server.ClearError();

It’s important to comment on all of your code so that if someone else has to use your error handling code, they understand the logic of the code.

ASP.NET Error Handling at Code Level

Try/catch coding is considered code level error handling and is something that all seasoned developers have likely already used. When an exception is thrown for different blocks of code, it will be handled inside of this coding.

A simple skeleton of how this coding may look is as follows:

try

{

//try coding

}

catch (FileNotFoundException e)

{

//catch 1

}

catch (System.IO.IOException e)

{

//catch 2

finally

{

    if (file != null)

    {

        file.Close();

    }

}

You can leave the coding for the “finally” logic in place unless you want to write to a log or take an additional action. Otherwise, you’ll only want to fill in the try, catch 1 and catch 2 coding to handle your logic.

The coding would look like the following:

  • Inside of the try coding you would add in:  file.ReadBlock(buffer, index, buffer.Length);
  • Inside your first catch 1, you would add in:  Server.Transfer(“error page URL”, true);
  • Inside the second catch, you would add in:  Server.Transfer(“IO ErrorPage”, true);

The first catch logic is for when the file isn’t found, and the second catch logic is when there’s a system IO error which is a bit more serious. 

How to Add Error Logging Support

Error logging helps developers and system admins better understand what’s happening internally with errors. There’s a lot of logic and coding that goes into error logging support. I recommend viewing this example from Microsoft.

Why would you want to log errors and exceptions?

Logging allows you to easily add additional logic that can be added to a database or a separate backend to find recurring errors. When troubleshooting is required in an application, you can choose to add more logic to understand the steps taken by the user that led to the error.

Tools like Stackify Retrace even combine errors and logs so that you can easily get to a trace with a performance issue without sifting through logs. 

When source code grows and more users are added to a site, it makes sense to have errors logged to rapidly respond to internal issues that may have been overlooked during the testing phase. A lot of functions and features may work well when they’re used as expected, but often errors are unexpected and never present during the quality assurance or testing phases.

Implementing an Application Performance Management tool, such as Stackify Retrace, allows you to proactively identify more issues in dev and QA and improve apps in production environments.   Retrace goes beyond standard APM to integrate errors and logs, server health metrics, and APM into one, easy to use platform.  Try your free, 14 day Retrace trial today.  

Common ASP.NET Errors

Developers may have to handle a number of errors when developing .NET projects. Some of the most common errors include:

NullReferenceException

The NullReferenceException will occur when attempting to use a class reference that’s set at null/Nothing with coding that expects otherwise. For example, you cannot call the method on strings that are set to null.

One way to avoid this error is by making sure that you build null checking into your coding and set default values. You can also use Debug.Assert to find the error before the exception occurs.

Broken WPF Data Bindings

Data bindings can save time in WPF, but can be a frustrating error to handle if they break. For example, if you have a TextBlock that’s missing data context, the error won’t show up in the output window.

One way to fix this error is to incorporate into the broken Debugger a Value Converter. TraceListener can also alert you when a data binding breaks.

Too Many Compiler Warnings

It’s tempting for developers to just hide warnings in the Error List window, but this can lead to an accumulation of ignored warnings. Eventually, these warnings can lead to code problems.

Unfortunately, there’s no quick fix for this problem. The best thing you can do is set aside time to address each warning individually. Although time-consuming, this practice can save you hours of time later on down the road.

StackOverflowException

A common .NET error can be compared to an OutOfMemoryException. It simply means that the code has surpassed a memory boundary. If there are too many memory allocations within a stack, an overflow exception occurs. Stacks are finite.

One way to avoid this common error is to try and ensure objects aren’t mutually referencing each other.

Data Binding Leak

There are several data binding options in WPF. When broken, these bindings can cause memory leaks within the application. This error can be detected by checking the dotMemory automatic inspections page for binding leaks.

One way to fix the problem is to make the object a DependencyProperty. 

DispatcherTimer Leak

Improper use of DispatcherTimer can cause a memory leak that leads to an error. For example, you may have a count variable that DispatcherTimer updates every second. The Dispatcher holds the reference, which means that UserControl is kept alive. This can cause a memory leak.

Fortunately, this is an easy fix. Simply stop the timer and set it to null.

Ultimately, when working with ASP.NET, it’s important to understand how to handle Application_error in the Global.asax file. It’s also important to understand how to handle other errors that can cause performance or function problems to ensure that you have a high quality, functioning application.  Ensure that you’re monitoring for errors in your application both in pre-production and production so you can catch the issues as soon as possible using an APM tool like Stackify Retrace

Improve Your Code with Retrace APM

Stackify's APM tools are used by thousands of .NET, Java, PHP, Node.js, Python, & Ruby developers all over the world.
Explore Retrace's product features to learn more.

Learn More

Want to contribute to the Stackify blog?

If you would like to be a guest contributor to the Stackify blog please reach out to [email protected]