在?ASP.NET?Core?中為?gRPC?服務(wù)添加全局異常處理
以下文章來源于公眾號:DotNetCore實戰(zhàn)
一、咨詢區(qū)
Dmitriy
在 ASP.NET Core 中使用GRPC.ASPNETCore 工具包寫 gRPC 服務(wù),想實現(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的跨機器通訊技術(shù),看得出 grpc 和 asp.net core 集成越來越好,是得需要大家花費精力好好學(xué)習(xí)。
到此這篇關(guān)于在 ASP.NET Core 中為 gRPC 服務(wù)添加全局異常處理 的文章就介紹到這了,更多相關(guān)在 ASP.NET Core 中為 gRPC 服務(wù)添加異常處理 內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用.NET 開發(fā)服務(wù)器 應(yīng)用管理工具
這篇文章主要介紹如何利用.NET 開發(fā)一個應(yīng)用管理工具的服務(wù)器,文章回先聊背景接著其是喲美好方法,需要的的小伙伴可以參考一下小面文章的具體內(nèi)容2021-10-10
ABP入門系列應(yīng)用BootstrapTable表格插件
Bootstrap table是一個開源的輕量級功能非常豐富的前端表格插件。下面通過本文給大家介紹ABP入門系列應(yīng)用BootstrapTable表格插件,感興趣的朋友一起學(xué)習(xí)吧2017-03-03
ASP.NET?Core?6最小API中使用日志和DI示例詳解
這篇文章主要為大家介紹了ASP.NET?Core?6最小API中使用日志和DI示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-08-08

