The .NET Stacks #57: 🧐 Taking a look at Blazor Error Boundaries
Tags: csharp, dotnet, azure
Published: 2021-07-19 13:06:54

---
title: The .NET Stacks #57: 🧐 Taking a look at Blazor Error Boundaries
published: true
date: 2021-07-18 23:00:00 UTC
tags: csharp,dotnet,azure
canonical_url: https://www.daveabrock.com/2021/07/18/dotnet-stacks-57/
---

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fu1s7nbbxamt9jc02c87.png)

Good morning, everybody. I hope everyone has had a good last couple of weeks, as I took last week off to celebrate Independence Day here in the United States.

Here's what we have this week:

- The big thing: Taking a look at Blazor Error Boundaries
- The little things: .NET Foundation elections, Minimal API improvements, pining to help with OSS?
- Last week in the .NET world

* * *

## The big thing: Taking a look at Blazor Error Boundaries

This weekend, I finished writing a piece on [Blazor error boundaries](https://devblogs.microsoft.com/aspnet/asp-net-core-updates-in-net-6-preview-4/#blazor-error-boundaries). It'll be published in a week or two, so here's a preview for you.

Looking at Blazor Server apps: when an unhandled exception occurs, Blazor Server treats it as a fatal error because the circuit hangs in an undefined state, which can potentially lead to usability or security problems. As a result, your app is as good as dead, loses its state, and your users are met with an undesirable _An unhandled error has occurred_ message, with a link to reload the page.

This begs the question: if I get an unhandled exception from a single component, why should my entire app die? As a Blazor developer, you're left spending a lot of time hacking around this by putting `try` and `catch` blocks around every single method of your app, leading to performance issues—especially when thinking about cascading parameters. Blazor developers [look longingly at React's Error Boundaries](https://reactjs.org/docs/error-boundaries.html) and wonder when we get to have nice things.

With .NET 6 Preview 4, you can. Inspired by Error Boundaries in React, it attempts to catch recoverable errors that can't permanently corrupt state—and like the React feature, it also renders a fallback UI. This capability won't catch all possible exceptions but most common scenarios such as the various lifecycle methods (like `OnInitializedAsync`, `OnParametersSetAsync`, and `OnAfterRenderAsync` ,  and rendering use cases with `BuildRenderTree`.

The new `ErrorBoundary` component provides a `ChildContent` fragment (what to display when all goes well), an `ErrorContent` fragment (what to display when it doesn't), and a `CurrentException` property so you can capture exception details.

Most importantly, the `ErrorBoundary` component allows you to call a `Recover` method, which resets the error boundary to a "non-errored state." By default, the component [handles up to 100 errors](https://github.com/dotnet/aspnetcore/blob/223d6e527cc98ce13fe45e4e14911013dd5ad807/src/Components/Components/src/ErrorBoundaryBase.cs#L31) through its `MaximumErrorCount` property. The `Recover` method [does three things for you](https://github.com/dotnet/aspnetcore/blob/223d6e527cc98ce13fe45e4e14911013dd5ad807/src/Components/Components/src/ErrorBoundaryBase.cs#L42): it resets the component's error count to `0`, clears the `CurrentException` and calls `StateHasChanged`. The `StateHasChanged` call [notifies components that the state has changed](https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-5.0#state-changes-statehaschanged) and typically causes your component to be rerendered.

Here's an example:

```csharp
@code {
    ErrorBoundary errorBoundary;

    protected override void OnParametersSet()
    {
        errorBoundary?.Recover();
    }
}
```

For another example, let's say you have a component that calls off to an API. Here, I'm getting a list of surfboards. I can wrap the data fetching in an `ErrorBoundary`.

```html
<tbody>
   @foreach (var board in ShirtProductsList)
   {
        <ErrorBoundary @key="@board">
            <ChildContent>
                <tr>
                   <td>@board.Id</td>
                   <td>@board.Name</td>
                   <td>@board.Color</td>
                   <td>@board.Price</td>
                 </tr>   
             </ChildContent>
             <ErrorContent>
                 Sorry, I can't show @board.Id because of an internal error.
             </ErrorContent>
         </ErrorBoundary>        
     }
</tbody>
```

Blazor Error Boundaries is not meant to be a global exception handling mechanism for any and all unhandled errors you encounter in your apps. You should be able to log all uncaught exceptions using the `ILogger` interface.

While you _can_ mark all your components with error boundaries and ignore exceptions, you should take a more nuanced approach to your application's error handling. Error Boundaries are meant for control over your specific component's unhandled exceptions and not a quick way to manage failures throughout your entire application. What do you think?

* * *

## The little things: .NET Foundation elections, Minimal API improvements, pining to help with a project?

The .NET Foundation will be holding elections next month for two upcoming Board seats. If you've [made it to the Elections page](https://dotnetfoundation.org/about/election/), you'll see my face as I'm on the Election Committee.

The .NET Foundation serves the general .NET community by promoting .NET in general, advocating .NET OSS, promoting .NET across a wider community of developers, supporting .NET community events, and offering administrative support to member projects. This is an organization that runs separately from Microsoft.

As a Board member, you'd help to run the .NET Foundation by deciding how the money is spent, decide which projects join the foundation, and much more. If you're interested in running for a seat, let me know and I'll get you started.

* * *

We've covered[Minimal APIs in .NET 6](https://www.telerik.com/blogs/low-ceremony-high-value-tour-minimal-apis-dotnet-6) a time or two. Prioritizing functions over classes, it's a route to simple APIs that many call ".NET Express"—I like the name because it describes getting right to the point and [one of the inspirations](http://expressjs.com/).

The examples have mostly been a little "Hello World"-ish. ASP.NET Core architect David Fowler shows that it's coming along:

{% twitter 1414248482743853058 %}

This `Results` class looks nice, especially if you aren't a fan of attributes for MVC controllers. I'm interested to see if it can be extended further, and [the team is looking into it](https://twitter.com/davidfowl/status/1414313120890114050).

If you're looking to extend model binding by using a single request object, you'll have to wait as it won't make it into .NET 6 ([but maybe .NET 7](https://twitter.com/davidfowl/status/1414290347992096773)). You can bind directly from the JSON object, but manually dealing with route and query parameters might get a tad unwieldy.

* * *

If you're looking to help with some open-source, David Pine could use some help. David has a project called the [Azure Cosmos DB Repository .NET SDK](https://github.com/IEvangelist/azure-cosmos-dotnet-repository), which allows you to use the repository pattern to work with your Cosmos DB instances. It really helps to simplify working with CRUD behavior in Cosmos, especially if you're familiar with the `IRepository<T>` interface. I find it quite nice, and use it for one of my projects ([and have written about it as well](https://www.daveabrock.com/2020/12/13/blast-off-blazor-cosmos/)).

David is working on a Blazor book for O'Reilly—if you've ever written a book or know someone who has, you won't be surprised to hear he'll need some help with the project. If you're interested in helping out, [let him know](https://twitter.com/davidpine7/status/1413140213992345610).

* * *

## 🌎 Last week in the .NET world

### 🔥 The Top 3

- Claudio Bernasconi [works on end-to-end UI testing using SpecFlow](https://www.claudiobernasconi.ch/2021/07/09/end-to-end-ui-testing-using-specflow/).
- Steve Gordon writes about the StringBuilder in [two](https://www.stevejgordon.co.uk/how-does-the-stringbuilder-work-in-dotnet-part-1) [posts](https://www.stevejgordon.co.uk/how-does-the-stringbuilder-work-in-dotnet-part-2). 
- Sam Walpole [writes about higher-order functions in C#](https://hackernoon.com/higher-order-functions-in-c-a-practical-example-ae6t35t7?source=rss).
- Leomaris Reyes [explores automation properties](https://askxammy.com/exploring-automation-properties-in-xamarin-forms/) in Xamarin.

### 📅 Community and events

- Colin Eberhardt [writes about GitHub Copilot](https://blog.scottlogic.com/2021/07/03/github-copilot-first-thoughts.html), and [so does Renato Losio](https://www.infoq.com/news/2021/07/github-copilot-pair-programmming/).
- Matthew MacDonald asks: [is Windows 11 a Better OS for developers?](https://medium.com/young-coder/is-windows-11-a-better-os-for-developers-ea268aa510a4)
- In community standups, we have Machine Learning [talking about model explainability](https://www.youtube.com/watch?v=oWsrWWCpseA) and Languages & Runtime [talks about what's coming up with the next .NET 6 previews](https://www.youtube.com/watch?v=J0LTqwTojlA).

### 🌎 Web development

- Matthew Jones [continues building a Solitaire game in Blazor](https://exceptionnotfound.net/solitaire-in-blazor-part-5-double-click-shortcut-and-autocomplete/).
- Andrew Lock [adds authentication to a Blazor Server app using Auth0](https://andrewlock.net/adding-authentication-to-a-blazor-server-app-using-auth0/).
- Vladimir Pecanac [writes about things to avoid in your ASP.NET Core controllers](https://code-maze.com/ten-things-avoid-aspnetcore-controllers/).
- Khalid Abuhakmeh [decrypts secrets into ASP.NET Core MVC action arguments using action filters](https://khalidabuhakmeh.com/decrypt-secrets-into-aspnet-core-mvc-action-arguments-using-action-filters).

### 🥅 The .NET platform

- Jason Bock [works on anagrams and prime numbers in .NET](https://medium.com/rocket-mortgage-technology-blog/anagrams-and-prime-numbers-20ba440704b0).
- Nick Randolph [writes about what it means to be a Windows app developer](https://nicksnettravels.builttoroam.com/i-am-a-windows-app-developer/).
- Patrick Smacchia [writes about some .NET 6 API updates and improvements](https://blog.ndepend.com/top-10-new-net-6-0-api/).
- Niels Swimberghe [creates a Discord Bot using the .NET worker template](https://swimburger.net/blog/azure/how-to-create-a-discord-bot-using-the-dotnet-worker-template-and-host-it-on-azure-container-instances).

### ⛅ The cloud

- Aaron Powell [continues his series of GraphQL on Azure](https://www.aaron-powell.com/posts/2021-07-05-graphql-on-azure-part-7-server-side-authentication/), [creates Azure Static Web Apps with F# and Fable](https://www.aaron-powell.com/posts/2021-07-09-creating-static-web-apps-with-fsharp-and-fable/), and also [controls the serialization of CosmosDB bindings for Azure Functions](https://www.aaron-powell.com/posts/2021-07-09-controlling-serialisation-of-cosmosdb-bindings-for-azure-functions/).
- Mark Heath [writes about dependency injection in Azure Durable Functions](https://markheath.net/post/durable-functions-di).
- Yohan Lasorsa [builds a shopping app with Azure Static Web Apps](http://azpodcast.azurewebsites.net/post/Episode-384-Safe-Deployment-Practices).

### 📔 Languages

- Davide Bellone [compares String.IsNullOrEmpty and String.IsNullOrWhiteSpace](https://www.code4it.dev/csharptips/string-isnullorempty-isnullorwhitespace).
- Ken Bonny [rediscovers implicit casting in C#](https://kenbonny.net/rediscovering-implicit-casting-1).
- Nikola M. Zivkovic [writes about upcoming C# 10 features](https://rubikscode.net/2021/07/05/c-10-top-5-new-features-in-the-upcoming-c-version/).
- Jason Roberts [writes about C# 9 foreach support](http://dontcodetired.com/blog/post/ICYMI-C-9-New-Features-Adding-foreach-Support-To-Any-Type).
- Sanjay Modi [writes about SOLID principles in C#](https://procodeguide.com/design/solid-principles-with-csharp-net-core/).

### 🔧 Tools

- Mark Downie [uses Visual Studio to search objects in a memory dump](https://www.poppastring.com/blog/using-visual-studio-to-search-objects-in-a-memory-dump).
- Raymond Chen asks: [what happens if I use a squash instead of a true merge?](https://devblogs.microsoft.com/oldnewthing/20210706-00/?p=105406)
- Joe Guadagno [tests Web APIs or services with JetBrains Rider](https://www.josephguadagno.net/2021/07/05/testing-web-apis-or-services-with-jetbrains-rider).
- Scott Hanselman [adds predictive IntelliSense to Windows Terminal](https://www.hanselman.com/blog/adding-predictive-intellisense-to-my-windows-terminal-powershell-prompt-with-psreadline).
- Alex Russell [writes about Git worktrees](https://infrequently.org/2021/07/worktrees-step-by-step/).
- Nick Randolph [converts an app from .NET MAUI to Uno](https://nicksnettravels.builttoroam.com/uno-weathertwentyone/).

### 🏗 Design, testing, and best practices

- Sarah Drasner [writes about running good meetings](https://css-tricks.com/good-meetings/).
- Peter Vogel [writes about best practices when mocking objects](https://www.telerik.com/blogs/mocking-101-first-principles-building-mock-objects).
- Sean Killeen [uses custom comparers in NUnit](https://seankilleen.com/2021/07/custom-comparers-in-nunit/).
- The Overflow writes about [the unexpected benefits of mentoring others](https://stackoverflow.blog/2021/07/07/the-unexpected-benefits-of-mentoring-others/).
- Derek Comartin [talks through a Clean Code architecture example](https://codeopinion.com/clean-architecture-example-breakdown/).

### 🎤 Podcasts

- The Coding Blocks Podcast [continues talking about the DDIA book](https://www.codingblocks.net/podcast/designing-data-intensive-applications-leaderless-replication/).
- The .NET Rocks Podcast [talks to Jeff Richter about Azure APIs](https://www.dotnetrocks.com/default.aspx?ShowNum=1747).
- Richard Lander [talks to the Azure DevOps Podcast](http://azuredevopspodcast.clear-measure.com/richard-lander-on-the-new-net-platform-episode-148).

### 🎥 Videos

- Shawn Wildermuth [explains dependency injection](https://wildermuth.com/2021/07/05/Coding-Shorts-Dependency-Injection-Explained).
- The On .NET Show [diagnoses thread pool exhaustion issues in .NET Core apps](https://channel9.msdn.com/Shows/On-NET/Diagnosing-thread-pool-exhaustion-issues-in-NET-Core-apps), [discusses Azure Functions with F#](https://www.youtube.com/watch?v=wBP8k1ZuRmQ), and also [talks about the null-coalescing assignment operator in C#](https://channel9.msdn.com/Shows/On-NET/C-Language-Highlights-Null-Coalescing-Assignment).