Blazor WASM Error Logging
blazor
20 Articles
In our previous article Blazor WASM Exception Handling and Error Boundary,
we learnt how global exception works and how to handle exceptions using built in ErrorBoundary
component. In this article, let's learn about Error Logging in Blazor WASM.
Logging is needed in all applications. This will help to find root cause or track user activity in any environment.
This can be done easily in server side applications with logging frameworks but for SPA
like Blazor WASM
running in browser sandbox,
we will not be having direct access to file system or database and logging cannot be done like how we do in server side applications. We can use
browser console to log Information
,
Warning
or
Error
. But this will not help much in production.
We can still make logging happen in production by processing Exception
and posting the error details to backend API.
Let's look on how to achieve this in Blazor WASM
.
Let's start with simple Subscription
component.
This will throw error on Subscribe Now
button click.
Code Sample - Subscribe component to simulate exception
To process the error, let's create an Error
component.
This component takes Child Content RenderFragment
as input.
This component also has ProcessError
method to process the
exception and log it to browser console
or
backend API
. For simplicity I'm logging into browser console.
Code Sample - Error component to log exception
Now lets wrap our Subscription
component with
Error
component.
Code Sample - Blazor Error logging with Error Component
That's it. Now if any exception occurs, Sunscription
component
will make use of CascadingParameter Error
component and process
the exception which then can be used to log to browser console or posted to backend API.
Demo - Error Logging
Scenario - Let's simulate an error logging when subscribing. Don't forget to check the browser console after clicking the below button