Error Boundaries in Blazor
This blog is going to explain what is Error Boundary in Blazor and how to implement it in the application. The Error Boundary is an easy way to handle the exception. If there is no error it will render the content, otherwise it will display the error message. Wrapping error Error Boundary component around the content will handle the unhandled exception.
Let’s see this with an example.
The following is the Index.razor page. Here I have added the Counter component covered by the <ErrorBoundary> component.
Index.razorTo demonstrate the error handling process. I have modified the existing IncrementCount() as follows. So when the user clicks the click me button it will throw out the exception.
The following image is the output of the code above. Here you can see that when the user clicks the button it shows an error message.
The error message and alert icon comes from the default Balzor template.
You can change it to wwwroot\css\site.css file if you wish.
Custom Error Message
You can customize the error message using the Error Boundary. See the code snippets below. Two more components <ChildContent> and <ErrorContent> are added here. You can write your custom error message within <ErrorContent>.
The following image is an output of the above code.
Also, you can catch the exact and detailed error using the context attribute of the ErrorBoundary component. In the below code snippets the Context=ex is added in the ErrorBoundary component.Therefore, it will display exception details.
The below image is an output of the above code. It shows the complete error details.
Error Boundary Recover Method
To set the non-error state, you can reset the status using the Recovery() method. For example, if an error occurs, the application will display the error. If the user fixes the error it will still show the error. To go non-error, you can use the Recover() method.
The image below is the output of the code snippet above. After clicking the Click me, the application displays an error message. After the user clicks the Recovery button, the application will move to an non-error state.
I hope this helps you. Keep coding.
Comments
Post a Comment