在非开发环境 Blazor 上抛出异常

问题描述 投票:0回答:1

我有一个在 .NET8 上编写的 Blazor 托管 WebAssembly 应用程序,因此有三个项目:客户端、服务器和共享。通过 Web API 调用进行相互通信。在我的剃刀组件中,我有以下代码将异常抛出到弹出模式窗口中:

任意函数中的代码:

if (!response.IsSuccessStatusCode)
{
    teamProcessing = false;
    var responseContent = await response.Content.ReadAsStringAsync();
    await ShowTheExceptionModal(responseContent);
}

异常功能

protected async Task ShowTheExceptionModal(string message)
{
    var options = new ModalOptions()
    {
        Size = ModalSize.Custom,
        SizeCustomClass = "bm-modal-custom"
    };
    var parameters = new ModalParameters();
    parameters.Add("message", message);
    var messageForm = modal.Show<Message_Modal>("Exception Error", parameters, options);
    var result = await messageForm.Result;
}

当 ASPNETCORE_ENVIRONMENT 为“开发”时,上述工作正常,但当 ASPNETCORE_ENVIRONMENT 为其他内容时,窗口会打开,但没有消息。我认为发生这种行为是因为异常可能提供敏感信息。我还读到,由于服务器的 Program.cs 上的代码,当 ASPNETCORE_ENVIRONMENT 不是“开发”时,有一个中间件。

if (app.Environment.IsDevelopment())
{
    app.UseWebAssemblyDebugging();
}
else
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

就我而言,我需要抛出这些异常,并且不更改应用程序内所有函数的代码,这是否可能?

exception blazor message blazor-webassembly throw
1个回答
0
投票

最后GPT在正确的提示下又做了一次,另外我在环境不是“开发”时做了一些处理以避免重大敏感信息,这是我解决这个问题的方法,但我也想听听你的意见!

一个新的 ExceptionHandlingMiddleware 类: 使用 System.Net;

namespace mynamespace.Server.Classes
{
    public class ExceptionHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlingMiddleware> _logger;

        public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                //EXCEPTION LOG
                _logger.LogError(ex, "An unhandled exception occurred.");
                //EXCEPTION PUSH INTO WEB CLIENT
                context.Response.ContentType = "application/json";
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                if (Parameters.enviroment == "Development")
                {
                    //This contains sensitive information
                    //ex.ToString() deserializes the whole object
                    string exception = ex.ToString();
                    await context.Response.WriteAsync(exception);
                }
                else
                {
                    //This does not contain sensitive information
                    string exception = ex.Message + Environment.NewLine + ex.StackTrace;
                    await context.Response.WriteAsync(exception);
                }

                //context.Response.Redirect("/Error"); //Redirect the exception
                //throw; //Rethrow the exception //Carefull here it might cause unpredicted behaviour as multiple iterations can happen.
            }
        }
    }
}

startup.cs 的新用法

app.UseMiddleware<ExceptionHandlingMiddleware>();
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.