Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 209
Dmitriy Avatar asked Oct 07 '19 21:10

Dmitriy


People also ask

How do I create a global exception handler?

Adding a Global Exception Handler The New Global Handler window opens. Type in a Name for the handler and save it in the project path. Click Create, a Global Exception Handler is added to the automation project.

What is global exception handling in ASP.NET Core?

Global exception handling with custom middleware grants the developer much broader authority and enhances the procedure. It's a block of code that can be added to the ASP.NET Core pipeline as middleware and holds our custom error handling mechanism.

How do I host a gRPC service?

net core console application by using the HostBuilder API to start building gRPC host and setting it up. By doing this, the generic host will automatically run StartAsync on our hosted service, which in turn will call StartAsync on the Server instance, essentially start the gRPC server.


1 Answers

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;
            }
        }
       
    }
}
like image 65
valentasm Avatar answered Sep 26 '22 00:09

valentasm