Home > Back-end >  Check exception type without considering T C#
Check exception type without considering T C#

Time:09-18

I have error class:

 public class FailureException<TRequest, TResponse> : PartialFailureException<TRequest, TResponse>
    {
        public FailureException(TRequest request, TResponse response, TRequest requestToRetry)
            : base(request, response, requestToRetry) { }
    }

And then I have different class to detect errors' types:

 public static class ErrorDetector
    {
        public static bool IsFailure(Exception e) =>
            e.GetType() == typeof(FailureException<TRequest, TResponse>));
    }

Is it possible to somwehow check type of error without adding FailureException<TRequest, TResponse> (just using FailureException) so that I wouldn't need to add <TRequest, TResponse> to bunch of other classes?

CodePudding user response:

I think you can check for the type with an open generic like this:

e.GetType().IsGenericType && e.GetType().GetGenericTypeDefinition() == typeof(FailureException<,>)

Here we don't specify the type arguments and instead check if the type is the generic type.

  • Related