I use Mediatr for an ASP.NET core project to handle all requests. I have several Request/Response/Handlers implemented. Each of them can throw a specific exception, let's call this "MyException" class. I defined an exception handler as
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);
}
}
I add this exception handler to the (Autofac) dependency container and this works if I throw a MyException in the MyHandler for MyRequest and MyResponse. However, I have dozens of requests, responses and corresponding handlers. So how can I register this exception handler for all of them for this specific exception (note: all responses are derived from a same base class). It tried something like the below, but, that does not get called. It only works if I give the actual types, but that would mean that I have to create an exception handler for each of the types, which is far from practical. Any ideas on how to solve this?
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);
}
}