失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > 如何在 ASP.NET Core 中为 gRPC 服务添加全局异常处理 ?

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

时间:2023-11-02 22:45:27

相关推荐

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

咨询区

Dmitriy

我在 Core 中使用GRPC.ASPNETCore工具包写 gRPC 服务,现在我想实现 gRPC 的异常全局拦截,我的代码如下:

app.UseExceptionHandler(configure=>{configure.Run(asynce=>{Console.WriteLine("Exceptiontestcode");});});

然后注入到 ServiceCollection 容器中。

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

奇怪的是,这段代码并不能实现拦截功能,我是真的不想让try-catch包裹所有的办法,太痛苦了。

回答区

valentasm

你可以给 gRPC 添加一个自定义拦截器,先看一下类定义。

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Threading.Tasks;usingGrpc.Core;usingGrpc.Core.Interceptors;usingMicrosoft.Extensions.Logging;namespaceSystemx.WebService.Services{publicclassServerLoggerInterceptor:Interceptor{privatereadonlyILogger<ServerLoggerInterceptor>_logger;publicServerLoggerInterceptor(ILogger<ServerLoggerInterceptor>logger){_logger=logger;}publicoverrideasyncTask<TResponse>UnaryServerHandler<TRequest,TResponse>(TRequestrequest,ServerCallContextcontext,UnaryServerMethod<TRequest,TResponse>continuation){//LogCall<TRequest,TResponse>(MethodType.Unary,context);try{returnawaitcontinuation(request,context);}catch(Exceptionex){//Note:Corelogging._logger.LogError(ex,$"Errorthrownby{context.Method}.");throw;}}}}

接下来就可以在 Startup 中通过AddGrpc注入啦。

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

点评区

grpc 早已经替代 wcf 成功一种基于tcp的跨机器通讯技术,看得出 grpc 和 core 集成越来越好,是得需要大家花费精力好好学习。

如果觉得《如何在 ASP.NET Core 中为 gRPC 服务添加全局异常处理 ?》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。