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

时间:2019-10-07 21:08:49

标签: c# asp.net-core .net-core grpc grpc-dotnet

我正在使用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");
    });
});

但是他们两个都不起作用(不是拦截代码)。

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

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

1 个答案:

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