How to handle exceptions in razor.cs files and display them globally in the console? BlazorWebAssembly

92 Views Asked by At

I want to create a middleware that will catch an error in the program if it occurs and display its information in the brower console.

What I mean is a functionality that will make it so that if an error appears in any of the razor.cs files, this functionality will write in the browser console such information about this error as its location and type of error. My question is which project's place in blazor web assembly application will be suitable for such middleware? Can it be program.cs ? Or is it possible to create such middleware so that it is in one place but affects all razor.cs files? Any suggestions?

1

There are 1 best solutions below

2
mRizvandi On

Use program.cs and Add your Middleware on the asp.net pipeline.

This is a sample AdvanceExceptionHandler:

namespace AryaVtd.Orca.Server.Infrastructure.Middlewares.Logging
{
    public class AdvancedExceptionHandler
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;
        private readonly IWebHostEnvironment _env;

        public AdvancedExceptionHandler(RequestDelegate next, ILoggerFactory logger, IWebHostEnvironment env)
        {
            _next = next;
            _logger = logger.CreateLogger(typeof(AdvancedExceptionHandler).Name);
            _env = env;
        }

        public async Task Invoke(HttpContext context)
        {
            string message = null;
            HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError;

            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                _logger.LogError($"AryaVtd.Orca.Server.Infrastructure.Middlewares.Logging:\r\nSource: {ex.Source} \r\nMessage: {ex.GetMessages()}");

                if (_env.IsDevelopment())
                {
                    var dic = new Dictionary<string, string>
                    {
                        ["StackTrace"] = ex.StackTrace,
                        ["Exception"] = ex.Message
                    };
                    message = JsonConvert.SerializeObject(dic);
                }
                else
                {
                    message = "AdvancedExceptionHandler: unfortunately an error has occurred on server!";
                }

                await WriteToReponseAsync();
            }

            async Task WriteToReponseAsync()
            {
                var exceptionResult = new ExceptionResult(message, (int)httpStatusCode);
                var result = JsonConvert.SerializeObject(exceptionResult);
                context.Response.StatusCode = (int)httpStatusCode;
                context.Response.ContentType = "application/json";

                await context.Response.WriteAsync(result);
            }
        }
    }

    public static class ExceptionHandlerMiddlewareExtension
    {
        public static void UseAdvancedExceptionHandler(this IApplicationBuilder app)
        {
            app.UseMiddleware<AdvancedExceptionHandler>();
        }
    }
}

Call the app.UseAdvancedExceptionHandler() in early of program.cs.

app.UseAdvancedExceptionHandler();