Hi, I Ihave a core class library project, where i locate global exception handler and other base classes
public class GlobalRequestExceptionHandler<TRequest, TResponse, TException>
: IRequestExceptionHandler<TRequest, TResponse, TException>
where TRequest : BaseRequest<TResponse>
where TResponse : BaseResponse
where TException : Exception
{
private readonly ILogger<GlobalRequestExceptionHandler<TRequest, TResponse, TException>> _logger;
public GlobalRequestExceptionHandler(
ILogger<GlobalRequestExceptionHandler<TRequest, TResponse, TException>> logger)
{
_logger = logger;
}
public Task Handle(TRequest request, TException exception, RequestExceptionHandlerState<TResponse> state,
CancellationToken cancellationToken)
{
_logger.LogError(exception, "Break here {@requestType}", typeof(TRequest));
throw new Exception("Exception");
}
}
public class BaseRequest<TResponse> : IRequest<TResponse> where TResponse : BaseResponse { }
public class BaseResponse
{
public bool HasError { get; set; }
public string Message { get; set; } = null!;
}
In another console project i set reference to this class library and a specific request and commands
public class FileUploadRequest : BaseRequest<FileUploadResponse>
{
public string FileName { get; set; }
}
public class FileUploadResponse : BaseResponse { }
public class FileUploadRequestHandler : IRequestHandler<FileUploadRequest, FileUploadResponse>
{
public Task<FileUploadResponse> Handle(FileUploadRequest request, CancellationToken cancellationToken)
{
throw new InvalidOperationException("My exception");
}
}
Make a registration in Program.cs of console app and make a request to IMediatr
var serviceCollection = new ServiceCollection();
serviceCollection.AddTransient(typeof(IRequestExceptionHandler<,,>), typeof(GlobalRequestExceptionHandler<,,>));
serviceCollection.AddMediatR(cfg =>
{
cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
});
var serilogLogger = new LoggerConfiguration()
.WriteTo.Console()
.CreateLogger();
serviceCollection.AddLogging(builder =>
{
builder.AddSerilog(logger: serilogLogger, dispose: true);
});
var serviceProvider = serviceCollection.BuildServiceProvider();
var services = serviceCollection;
var mediator = serviceProvider.GetRequiredService<IMediator>();
var result = await mediator.Send(new FileUploadRequest()
{
FileName = "FileName"
});
Console.ReadLine();
Expected: exception hit the Handle method of GlobalRequestExceptionHandler
Actual: Handle method of GlobalRequestExceptionHandler skipped
Hi, I Ihave a core class library project, where i locate global exception handler and other base classes
In another console project i set reference to this class library and a specific request and commands
Make a registration in Program.cs of console app and make a request to IMediatr
Expected: exception hit the Handle method of GlobalRequestExceptionHandler Actual: Handle method of GlobalRequestExceptionHandler skipped