gpt4 book ai didi

c# - 如何在 Mediatr 中为所有请求定义一个特定的异常处理程序

转载 作者:行者123 更新时间:2023-12-01 23:38:07 29 4
gpt4 key购买 nike

我将 Mediatr 用于 ASP.NET 核心项目来处理所有请求。我实现了几个请求/响应/处理程序。它们中的每一个都可以抛出一个特定的异常,我们称这个为“MyException”类。我将异常处理程序定义为

    public class MyExceptionHandler : RequestExceptionHandler<MyRequest<MyResponse>, MyResponse, MyException>
{
protected override void Handle(MyRequest<MyResponse> request, MyException exception, RequestExceptionHandlerState<MyResponse> state)
{
MyResponse response = new MyResponse();
//Set some specific properties here in the response to indicate an error occurred
state.SetHandled(response);
}
}

我将此异常处理程序添加到 (Autofac) 依赖项容器中,如果我在 MyRequest 和 MyResponse 的 MyHandler 中抛出 MyException,这将起作用。但是,我有几十个请求、响应和相应的处理程序。那么我如何为这个特定的异常注册这个异常处理程序呢(注意:所有的响应都来自同一个基类)。它尝试了类似下面的内容,但是没有被调用。它只有在我给出实际类型时才有效,但这意味着我必须为每种类型创建一个异常处理程序,这远非实用。关于如何解决这个问题的任何想法?

    public class MyExceptionHandler : RequestExceptionHandler<IRequest<BaseResponse>, BaseResponse, MyException>
{
protected override void Handle(IRequest<BaseResponse> request, MyException exception, RequestExceptionHandlerState<BaseResponse> state)
{
BaseResponse response = new BaseResponse();
//Set some specific properties here in the response to indicate an error occurred
state.SetHandled(response);
}
}

最佳答案

你可以像这样创建一个通用的:

public class ExceptionLoggingHandler<TRequest, TResponse, TException> : IRequestExceptionHandler<TRequest, TResponse, TException>
where TRequest : IRequest<TResponse>
where TException : Exception
{
private readonly ILogger<ExceptionLoggingHandler<TRequest, TResponse, TException>> _logger;

public ExceptionLoggingHandler(ILogger<ExceptionLoggingHandler<TRequest, TResponse, TException>> logger)
{
_logger = logger;
}

public Task Handle(TRequest request, TException exception, RequestExceptionHandlerState<TResponse> state, CancellationToken cancellationToken)
{
_logger.LogError(exception, "Something went wrong while handling request of type {@requestType}", typeof(TRequest));

// TODO: when we want to show the user somethig went wrong, we need to expand this with something like
// a ResponseBase where we wrap the actual response and return an indication whether the call was successful or not.
state.SetHandled(default!);

return Task.CompletedTask;
}
}

然后像这样在 IerviceC 上注册它:

services.AddTransient(typeof(IRequestExceptionHandler<,,>), typeof(ExceptionLoggingHandler<,,>))

因为 RequestExceptionProcessorBehavior类将使用 3 个泛型查找此类型,而不是 IRequestExceptionHandler<,>一个。

关于c# - 如何在 Mediatr 中为所有请求定义一个特定的异常处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65297156/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com