我正在使用GRPC.ASPNETCore使用ASP.NET Core编写gRPC服务。
我试图为这样的gRPC方法添加一个异常过滤器
services.AddMvc(options =>
{
options.Filters.Add(typeof(BaseExceptionFilter));
});
或使用像这样的UseExceptionHandler
扩展方法
app.UseExceptionHandler(configure =>
{
configure.Run(async e =>
{
Console.WriteLine("Exception test code");
});
});
但是他们两个都不起作用(不是拦截代码)。
我不想为我要调用的每种方法编写try-catch
代码包装器。
答案 0 :(得分:5)
在启动中添加自定义拦截器
services.AddGrpc(options =>
{
{
options.Interceptors.Add<ServerLoggerInterceptor>();
options.EnableDetailedErrors = true;
}
});
创建自定义类。
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;
}
}
}
}