I'm playing around with building a factory method for generating RuntimeExceptions.
The idea would be to throw an exception by performing the following snippet:
throw ExceptionFactory.build(CustomException.class, CustomException.NOT_FOUND);
The first parameter to the build method is the exception class, however the second parameter would reference an Enum that's defined within the CustomException class for loading up additional details when building the exception.
Example:
public class CustomException extends RuntimeException {
public static final ExceptionType NOT_FOUND = ExceptionType.NOT_FOUND;
//constructors, getters, setters, etc..
private enum ExceptionType {
NOT_FOUND(Status.NOT_FOUND, "These aren't the droids you're looking for!");
private Status status;
private String description;
private ExceptionType(Status status, String description){
this.status = status;
this.description = description;
}
//other methods here..
}
}
The question I have is with the ExceptionFactory.build(), how do I specify the parameters for the build() method such that the second parameter must be specific to the CustomException class?
If this approach sounds crazy, how could it be improved? The goal is to have a generic factory method for building exceptions that have details already pre loaded. What I want is to avoid is something like this..
ExceptionFactory.build(CustomException.class, "Some string...")
The idea is the description needs to be defined in the CustomException and not just anything when throwing the error. So how to enforce??
public class ExceptionFactory {
public static <T extends RuntimeException> T build(T e, ???){
//more logic here...
}
}
throw FooException.NOT_FOUND.build(). the enum contains all info necessary to build the exception. or justthrow FooException.notFound()throw ExceptionFactory.build(FooException.class, FooException.NOT_FOUND)is an improvement over justthrow new FooException(FooException.NOT_FOUND)