如何在 ASP.NET Core 中为 gRPC 服务添加全局异常处理程序?

How to add global exception handler for gRPC services in ASP.NET Core?

我正在使用 ASP.NET 核心编写 gRPC 服务,使用 GRPC.ASPNETCore。

我试过像这样为 gRPC 方法添加异常过滤器

services.AddMvc(options =>
{
    options.Filters.Add(typeof(BaseExceptionFilter));
});

或像这样使用 UseExceptionHandler 扩展方法

app.UseExceptionHandler(configure =>
{
    configure.Run(async e =>
    {
        Console.WriteLine("Exception test code");
    });
});

但是两者都不行(不是拦截代码)

是否可以在 ASP.NET Core 中为 gRPC 服务添加全局异常处理程序?

我不想为我想调用的每个方法编写 try-catch 代码包装器。

在启动中添加自定义拦截器

services.AddGrpc(options =>
{
    {
        options.Interceptors.Add<ServerLoggerInterceptor>();
        options.EnableDetailedErrors = true;
    }
});

创建自定义 class。

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;
            }
        }
       
    }
}