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).
I don't want to write try-catch
code wrapper for each method I want to call.
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.
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.
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.
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;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With