日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

在?ASP.NET?Core?中為?gRPC?服務(wù)添加全局異常處理_ASP.NET

作者:DotNetCore實(shí)戰(zhàn) ? 更新時間: 2022-03-25 編程語言

以下文章來源于公眾號:DotNetCore實(shí)戰(zhàn)

一、咨詢區(qū)

Dmitriy

ASP.NET Core 中使用GRPC.ASPNETCore 工具包寫 gRPC 服務(wù),想實(shí)現(xiàn) gRPC 的異常全局?jǐn)r截,

代碼如下:

app.UseExceptionHandler(configure =>
{
? ? configure.Run(async e =>
? ? {
? ? ? ? Console.WriteLine("Exception test code");
? ? });
});

然后注入到 ServiceCollection 容器中:

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

奇怪的是,這段代碼并不能實(shí)現(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;
? ? }
});

三、點(diǎn)評區(qū)

grpc 早已經(jīng)替代 wcf 成功一種基于tcp的跨機(jī)器通訊技術(shù),看得出 grpc 和 asp.net core 集成越來越好,是得需要大家花費(fèi)精力好好學(xué)習(xí)。

相關(guān)推薦

欄目分類
最近更新