在?ASP.NET?Core?中為?gRPC?服務添加全局異常處理
以下文章來源于公眾號:DotNetCore實戰(zhàn)
一、咨詢區(qū)
Dmitriy
在 ASP.NET Core
中使用GRPC.ASPNETCore
工具包寫 gRPC
服務,想實現(xiàn) gRPC
的異常全局攔截,
代碼如下:
app.UseExceptionHandler(configure => { ? ? configure.Run(async e => ? ? { ? ? ? ? Console.WriteLine("Exception test code"); ? ? }); });
然后注入到 ServiceCollection 容器中:
services.AddMvc(options => { ? ? options.Filters.Add(typeof(BaseExceptionFilter)); });
奇怪的是,這段代碼并不能實現(xiàn)攔截功能,我是真的不想讓 try-catch 包裹所有的辦法,太痛苦了。
二、回答區(qū)
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; ? ? ? ? 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; ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? ? ? } }
接下來就可以在 Startup 中通過 AddGrpc 注入啦:
services.AddGrpc(options => { ? ? { ? ? ? ? options.Interceptors.Add<ServerLoggerInterceptor>(); ? ? ? ? options.EnableDetailedErrors = true; ? ? } });
三、點評區(qū)
grpc
早已經(jīng)替代 wcf
成功一種基于tcp
的跨機器通訊技術,看得出 grpc 和 asp.net core 集成越來越好,是得需要大家花費精力好好學習。
到此這篇關于在 ASP.NET Core 中為 gRPC 服務添加全局異常處理 的文章就介紹到這了,更多相關在 ASP.NET Core 中為 gRPC 服務添加異常處理 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
ASP.NET?Core?6最小API中使用日志和DI示例詳解
這篇文章主要為大家介紹了ASP.NET?Core?6最小API中使用日志和DI示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08