提问人:userxchange123 提问时间:5/29/2023 最后编辑:userxchange123 更新时间:6/1/2023 访问量:61
如何处理 razor.cs 文件中的异常并在控制台中全局显示它们?BlazorWebAssembly
How to handle exceptions in razor.cs files and display them globally in the console? BlazorWebAssembly
问:
我想创建一个中间件,如果发生错误,它将捕获程序中的错误,并在浏览器控制台中显示其信息。
我的意思是一个功能,如果任何razor.cs文件中出现错误,此功能将在浏览器控制台中写入有关此错误的信息,例如其位置和错误类型。我的问题是哪个项目在 blazor Web 程序集应用程序中的位置适合此类中间件?它可以是程序 .cs 吗?或者是否可以创建这样的中间件,使其位于一个地方,但影响所有razor.cs文件?有什么建议吗?
答:
0赞
mRizvandi
6/1/2023
#1
使用 program.cs 并在 asp.net 管道上添加中间件。
下面是一个示例 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>();
}
}
}
调用应用。UseAdvancedExceptionHandler() 在程序 .cs 的早期。
app.UseAdvancedExceptionHandler();
评论
0赞
userxchange123
6/12/2023
我可以把它放在客户端程序 .cs 类中吗?还是服务器端?
0赞
mRizvandi
6/15/2023
它的中间战争,你必须在服务器端使用它。
评论