Dmi*_*riy 6 c# .net-core grpc asp.net-core grpc-dotnet
我正在使用 GRPC.ASPNETCore 使用 ASP.NET Core 编写 gRPC 服务。
我试图为这样的 gRPC 方法添加一个异常过滤器
services.AddMvc(options =>
{
options.Filters.Add(typeof(BaseExceptionFilter));
});
Run Code Online (Sandbox Code Playgroud)
或使用这样的UseExceptionHandler扩展方法
app.UseExceptionHandler(configure =>
{
configure.Run(async e =>
{
Console.WriteLine("Exception test code");
});
});
Run Code Online (Sandbox Code Playgroud)
但是它们都不起作用(不拦截代码)。
我不想为try-catch我想调用的每个方法编写代码包装器。
在启动中添加自定义拦截器
services.AddGrpc(options =>
{
{
options.Interceptors.Add<ServerLoggerInterceptor>();
options.EnableDetailedErrors = true;
}
});
Run Code Online (Sandbox Code Playgroud)
创建自定义类。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Grpc.Core;
using Grpc.Core.Interceptors;
using Microsoft.Extensions.Logging;
namespace Systemx.WebService.Services
{
public class ServerLoggerInterceptor : Interceptor
{
private readonly ILogger<ServerLoggerInterceptor> _logger;
public ServerLoggerInterceptor(ILogger<ServerLoggerInterceptor> logger)
{
_logger = logger;
}
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
TRequest request,
ServerCallContext context,
UnaryServerMethod<TRequest, TResponse> continuation)
{
//LogCall<TRequest, TResponse>(MethodType.Unary, context);
try
{
return await continuation(request, context);
}
catch (Exception ex)
{
// Note: The gRPC framework also logs exceptions thrown by handlers to .NET Core logging.
_logger.LogError(ex, $"Error thrown by {context.Method}.");
throw;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4123 次 |
| 最近记录: |