Reader small image

You're reading from  ASP.NET 8 Best Practices

Product typeBook
Published inDec 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781837632121
Edition1st Edition
Languages
Right arrow
Author (1)
Jonathan R. Danylko
Jonathan R. Danylko
author image
Jonathan R. Danylko

Jonathan "JD" Danylko is an award-winning, full-stack ASP.NET architect. He's used ASP.NET as his primary way to build websites since 2002 and before that, Classic ASP. Jonathan contributes to his blog (DanylkoWeb) on a weekly basis, has built a custom CMS, is a founder of Tuxboard (an open-source ASP.NET dashboard library), has been on various podcasts, and guest posted on the C# Advent Calendar for 6 years. Jonathan has worked in various industries for small, medium, and Fortune 100 companies, but currently works as an Architect at Insight Enterprise. The best way to contact Jonathan is through GitHub, LinkedIn, Twitter, email, or through the website.
Read more about Jonathan R. Danylko

Right arrow

Catching Exceptions with Exception Handling

We always try to make our code as stable as possible when building web applications, but there are times when we can’t catch everything. This is why exceptions are considered a foundational part of development. Exception handling is essential for preventing web applications from crashing and displaying an ugly error message on a page. It’s tempting to wrap everything with try/catch or try/finally statements and move on. This should be avoided. Coding with try/catch/finally statements in an application should be the exception to the rule.

The common coding standards in this chapter are meant to remove those types of scenarios and provide a better developer experience.

In this chapter, we’ll examine what exception handling means to developers and when to use it, along with where to handle global exceptions and examine performance considerations. Once we understand the basics of exception handling, the last section...

Technical requirements

We recommend using a favorite editor to add the exception handling code snippets throughout this chapter. Our recommendations are as follows:

  • Visual Studio (preferably the latest version)
  • Visual Studio Code
  • JetBrains Rider

The editor we’ll be using is Visual Studio 2022 Enterprise, but any version (Community or Professional) will work with the code.

Using exception handling

In this section, we’ll discuss what exception handling is, the two types of error handling, when to use error handling in an application, and how exceptions affect performance.

What is exception handling?

Exception handling is the ability to recover gracefully from unexpected situations in the code during runtime; how do we handle errors or problems we experience in applications? It also involves cleaning up allocated resources when issues occur to avoid memory leaks.

There are two types of errors:

  • Runtime errors: These are unexpected errors we experience when running the application.
  • Manual: These are intentional errors that are thrown based on a condition (for instance, ArgumentNullException.ThrowIfNull() at the beginning of a method to confirm whether a parameter is null or not).

Since this book focuses on intermediate to advanced developers, we’re assuming debugging an ASP.NET application is a common process; we...

Handling global exceptions

As mentioned earlier in this chapter, we can only handle so many errors when it comes to web applications. But what if we want to provide a catch-all for all unhandled exceptions?

For global exceptions, we need to revisit the middleware. There is a method called UseExceptionHandler() in the Startup.cs file that points to a /Error page (either Razor or MVC), as shown in the following code snippet:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

Pay particular attention to the env.IsDevelopment() condition. The /Error page is meant for non-development viewing only. As we mentioned back in Chapter 4 regarding security, always be careful what to show on this page. It may expose system data such as a database connection string that contains credentials or other sensitive data.

To access the exception...

Performance considerations

One common myth about exception handling is that it doesn’t affect performance. If exceptions are significantly harming the application’s performance, that’s a sign that exceptions are being used too much. Exceptions should not control the flow of the application whatsoever.

Ideally, the code should flow with no interruptions. In small web applications with a few users, this type of approach may be adequate, but for high-performing, high-traffic websites, placing a try/catch block in frequently-called code may cause the site to suffer a performance hit.

In this section, we covered what exception handling was, reviewed the two types of errors in applications, identified where exception handling is ideal, and covered some of the performance myths regarding exceptions. Next, we’ll look at some common exception handling techniques.

Common exception handling techniques

Exceptions are expensive in .NET. When an exception occurs in the application, there are resources in place to begin the error handling process when an exception occurs, such as the stack trace process. Even when we are catching and handling the errors, ASP.NET is still creating the Exception object and everything associated with it along with walking up the call stack to locate the handler.

In this section, we’ll look at common approaches in the industry to minimize the exceptions through “prevention before exception,” why to use logging, why unit testing is similar to exception handling, why empty catch blocks should be avoided, how to simplify exceptions using exception filtering and pattern matching, why blocks are important when releasing resources, and how to rethrow exceptions properly.

Prevention before exception

As we said in the previous section, exceptions interrupt the flow of an application when encountered...

Summary

Exception handling is important but requires a level of experience when writing truly robust applications. Applications need to recover so that the user doesn’t have a jarring experience.

In this chapter, we learned about exception handling, when to use it, and where it makes sense, as well as performance considerations.

We ended this chapter by learning about the common techniques of exception handling by understanding the “prevention before exception” principle, why logging is important, and why exception handling is like unit testing.

We also learned that empty catch blocks are wasteful, how to simplify exceptions using exception filtering and pattern matching, when to use finally blocks, and how to rethrow exceptions properly.

In the next chapter, we’ll look at web API standards and how they are extremely important to the ASP.NET Core ecosystem.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
ASP.NET 8 Best Practices
Published in: Dec 2023Publisher: PacktISBN-13: 9781837632121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Jonathan R. Danylko

Jonathan "JD" Danylko is an award-winning, full-stack ASP.NET architect. He's used ASP.NET as his primary way to build websites since 2002 and before that, Classic ASP. Jonathan contributes to his blog (DanylkoWeb) on a weekly basis, has built a custom CMS, is a founder of Tuxboard (an open-source ASP.NET dashboard library), has been on various podcasts, and guest posted on the C# Advent Calendar for 6 years. Jonathan has worked in various industries for small, medium, and Fortune 100 companies, but currently works as an Architect at Insight Enterprise. The best way to contact Jonathan is through GitHub, LinkedIn, Twitter, email, or through the website.
Read more about Jonathan R. Danylko