Turn on CircuitOption.DetailedError in Blazor

Turn on CircuitOption.DetailedError in Blazor

This article is going to explain how to enable CircuitOption.DetailedError in the development environment.

Let us look at a small example. The following is the Blazor component code. It contains both HTML and @code block. GetArray() method is defined in the @code module. In it, the array is initialized with four elements.  Finally, arr [5] is assigned to the result variable so that it triggers an index outside the range exception.

@page “/”

<h4>Turn on CircuitOption.DetailedError</h4>

<button @onclick=”GetArray”>Trigger the Exception</button>

@code
{
    void GetArray()
    {
        int[] arr = new int[] { 1, 2, 3, 4 };
        int result = arr[5];
    }
}

The following screenshot illustrates how the exception is displayed in the browser. It states, Error: There was an unhandled exception on the current circuit, so this circuit will be terminated. For more details turn on detailed exceptions in ‘CircuitOptions.DetailedErrors’.

CircuitOption.DetailedError

Let us see how to enable the CircuitOption.DetailedError.

In the Startup.cs file, IWebHostEnvironment  is initialized to provide web hosting environment information. Added  IWebHostEnvironment  in Startup constructor. Finally, AddCircuitOptions has been added in the ConfigureServices method, which helps to configure circuits.

In this code _Env.Is Development () is checked to confirm if it is a development environment or not. If it is a development environment, then only it will display the detail error.

private readonly IWebHostEnvironment _env;

public Startup(IConfiguration configuration, IWebHostEnvironment env)
{
    Configuration = configuration;
    _env = env;
}

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddServerSideBlazor().AddCircuitOptions(options => {
       if (_env.IsDevelopment())
      {
        options.DetailedErrors = true;
      }
    });

    services.AddSingleton<WeatherForecastService>();
}

The following screenshot illustrates how the browser displays the error after enabling a detailed error. It clearly states what the error is and shows which file it is and which line number it occurs.

CircuitOption.DetailedError

The blog explains how to enable CircuitOption.DetailedError in the development environment.

If you have any questions, please leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *