Dmitriy
Dmitriy

Reputation: 937

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

I'm writing gRPC services using ASP.NET Core using GRPC.ASPNETCore.

I've tried to add an Exception Filter for gRPC methods like this

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

or using the UseExceptionHandler extension method like this

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

But both of them are not working (not intercepting code).

Is it possible to add global exception handler for gRPC services in ASP.NET Core?

I don't want to write try-catch code wrapper for each method I want to call.

Upvotes: 12

Views: 10645

Answers (1)

valentasm
valentasm

Reputation: 2402

Add custom interceptor in Startup

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

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

Upvotes: 20

Related Questions