Reader small image

You're reading from  Mastering Blazor WebAssembly

Product typeBook
Published inAug 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803235103
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Ahmad Mozaffar
Ahmad Mozaffar
author image
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar

Right arrow

Handling Errors in Blazor WebAssembly

You are working hard on the client side, you have built an amazing app that does everything perfectly, the UI is great, your app is fetching and sending data from and to the API correctly, and everyone is happy. But what if the API, for some reason, is taking too long to process requests, so your app loads for around 30 seconds, then a yellow bar appears at the bottom, indicating that an unhandled exception occurred? That’s an experience that neither the user nor the developer would like to have.

Errors and exceptions can occur for many reasons and in many parts of an app. The goal of this chapter is to learn the techniques to handle them properly and give users a better experience. We will start by explaining why error handling matters and then how to manage the errors that could arise from communication with the API. Then, we will build a global error handler, where all errors will be handled and processed properly. Finally, we will...

Technical requirements

The Blazor WebAssembly code and the API project used throughout this chapter are available in the book’s GitHub repository in the Chapter 11 folder:

https://github.com/PacktPublishing/Mastering-Blazor-WebAssembly/tree/main/Chapter_10/

Make sure to have the API solution up and running beside the Blazor one.

Understanding error handling

Failures can show up in many parts of the app, either due to some lack of handling for the business logic or due to external circumstances such as the API being unreachable. The process of reacting to those errors gracefully without letting them crash the app is what’s called error handling.

Errors don’t always imply bad code or incorrect logic; these are just some of the causes of errors. Sometimes, the business logic of the app forces an error to be shown if the user is violating the rules. Other errors can be caused by external circumstances, such as the API being down. Writing good code can prevent programming errors. For example, if you are accessing a null object, that will throw a NullReferenceException, but this exception is avoidable with better code management.

Let’s take an example of a feature that imports data into the system. The user can upload a file, and the logic of the feature forces this file to be either an...

Managing API errors

APIs are the main source of headaches in the project. API calls happen through the network and the potential for failure always exists. The API could respond differently based on the status of the response, and other scenarios could occur, such as the server being down, unhandled exceptions occurring while processing the request, or authentication and authorization errors.

For all these reasons, it’s very important to handle API requests carefully. The starting point is to understand at each point what could go wrong and what the appropriate response is in each case. If you are the developer of the API, things are easier, but if you are not, the documentation should be the main source of truth.

The BooksStore API has the Swagger page that we used in previous chapters to understand the input and output of some API endpoints. We noticed that the endpoints either succeed or retrieve the 400 Bad Request status code, which means something went wrong on the...

Implementing global error handlers

Having a global error handler gives you a centralized place to handle all errors the same way. This will also allow centralized logging. Errors such as API request timeouts, internal server errors, or any other unexpected scenarios will be handled here. Handling them will consist of showing a readable message to the user, indicating that something went wrong and logging the error.

We will use cascading parameters to create an error handler component for our app. This component will be placed in the App.razor file and will wrap all the other app components. It will have a method that takes an exception as a parameter and processes it accordingly. By using a cascading parameter, we can provide the error handler component as an object for all the descendant components in our app. With that, any component can have access to the handler instance and will be able to call the handle method exception.

Let’s implement the flow and use it within...

Utilizing the ErrorBoundary component

In .NET 6.0, Blazor got a new component called ErrorBoundary. This component is very simple, easy to use, and powerful at the same time. The ErrorBoundary component handles any exceptions that occur during the rendering of a child component and displays a custom UI in place of the faulty component.

The ErrorBoundary component accepts two RenderFragement parameters: one called ChildContent, which represents the UI of the child components when no errors occur, and another called ErrorContent, which represents the content when an error occurs.

For example, when you use Twitter with a poor internet connection, you may see that the tweet details load successfully, but the replies below the tweet display an error message such as Failed to load the replies with a Retry button. This experience can be achieved with the ErrorBoundary component, but you need to keep in mind that the exception you need to handle with the ErrorBoundary error UI must not...

Summary

After reading this chapter, you should be able to build an app that functions properly and delivers user value from the logic, UI, and reliability perspectives.

We started the chapter by talking about the importance of handling errors efficiently in your Blazor WebAssembly app. We started by going over how to handle the possible API responses, and then we implemented a global error handler that centralizes the processing of an exception. In the last section, we covered a cool component that’s built for error handling from a UI perspective called ErrorBoundary. We demonstrated how we can use it and showed its capabilities.

After completing this chapter, you should be able to do the following:

  • Understand the crucial need of handling error errors in single-page applications
  • Handle failure requests when calling an API endpoint
  • Build a centralized error handler that can be used across all the components
  • Know how and when to use the ErrorBoundary...
lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mastering Blazor WebAssembly
Published in: Aug 2023Publisher: PacktISBN-13: 9781803235103
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
Ahmad Mozaffar

Ahmad Mozaff ar is a senior soft ware engineer, cloud developer, and trainer who currently works at ContraForce as a senior full stack engineer responsible for developing SaaS platforms using Blazor, Azure, AI, and other modern technologies. Originally from Syria, his passion for soft ware development, especially .NET and Azure, started at a very early age. He loves teaching people about developing soft ware using .NET, Azure, and other Microsoft technologies through his YouTube channel, AK Academy, and writing articles on multiple platforms, which have reached more than 400K readers.
Read more about Ahmad Mozaffar