ASCII码 ASCII码

在 ASP.NET Core 中为 gRPC 服务添加全局异常处理

发布于:2022-01-09 11:53:28  栏目:技术文档

目录一、咨询区Dmitriy二、回答区valentasm三、点评区以下文章来源于公众号:DotNetCore实战

一、咨询区

Dmitriy在 ASP.NET Core 中使用GRPC.ASPNETCore 工具包写 gRPC 服务,想实现 gRPC 的异常全局拦截,

代码如下:app.UseExceptionHandler(configure => { configure.Run(async e => { Console.WriteLine("Exception test code"); }); });然后注入到 ServiceCollection 容器中:services.AddMvc(options => { options.Filters.Add(typeof(BaseExceptionFilter)); });奇怪的是,这段代码并不能实现拦截功能,我是真的不想让 try-catch 包裹所有的办法,太痛苦了。

二、回答区

valentasm我们可以给 gRPC 添加一个自定义拦截器,先看一下类定义:`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;

  1. public ServerLoggerInterceptor(ILogger<ServerLoggerInterceptor> logger)
  2. {
  3. _logger = logger;
  4. }
  5. public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
  6. TRequest request,
  7. ServerCallContext context,
  8. UnaryServerMethod<TRequest, TResponse> continuation)
  9. {
  10. //LogCall<TRequest, TResponse>(MethodType.Unary, context);
  11. try
  12. {
  13. return await continuation(request, context);
  14. }
  15. catch (Exception ex)
  16. {
  17. // Note: The gRPC framework also logs exceptions thrown by handlers to .NET Core logging.
  18. _logger.LogError(ex, $"Error thrown by {context.Method}.");
  19. throw;
  20. }
  21. }
  22. }

}接下来就可以在 Startup 中通过 AddGrpc 注入啦:services.AddGrpc(options =>{ { options.Interceptors.Add<ServerLoggerInterceptor>(); options.EnableDetailedErrors = true; }});`三、点评区grpc 早已经替代 wcf 成功一种基于tcp的跨机器通讯技术,看得出 grpc 和 asp.net core 集成越来越好,是得需要大家花费精力好好学习。

相关推荐
阅读 +