在?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?中為?gRPC?服務添加全局異常處理
這篇文章主要介紹了在?ASP.NET?Core?中為?gRPC?服務添加全局異常處理?,在?ASP.NET?Core?中使用?GRPC.ASPNETCore?工具包寫?gRPC?服務,想實現(xiàn)?gRPC?的異常全局攔截,下面一起來看看文中的詳細內(nèi)容吧2022-01-01
ASP.NET webUploader上傳大視頻文件相關web.config配置
本文主要介紹了webUploader上傳大視頻文件相關web.config的配置。具有一定的參考價值,下面跟著小編一起來看下吧2017-01-01
ASP.NET?Core使用Middleware設置有條件允許訪問路由
這篇文章主要介紹了ASP.NET?Core使用Middleware設置有條件允許訪問路由,文章圍繞主題相關資料展開學習內(nèi)容,需要的小伙伴可以參考一下,希望對你的學習有所幫助2022-02-02
.Net 7函數(shù)Ctor與CCtor使用及區(qū)別詳解
這篇文章主要為大家介紹了.Net 7函數(shù)Ctor與CCtor使用及區(qū)別詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-11-11

