好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

以下文章来源于公众号: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;

? ? ? ? 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;
? ? }
});

三、点评区

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

到此这篇关于在 ASP.NET Core 中为 gRPC 服务添加全局异常处理 的文章就介绍到这了,更多相关在 ASP.NET Core 中为 gRPC 服务添加异常处理 内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于在 ASP.NET Core 中为 gRPC 服务添加全局异常处理的详细内容...

  阅读:48次