lundi 2 août 2021

Intercept method exceptions in java

I wanted to know if it is possible to make something like that to intercept errors when calling a method and how, or if there is something already created similar... example so you can understand better.

ErrorMessageHandler.intercept(RepositoryManager.find(Types.valueOf("NONE"), "test")
            .interceptExceptionWithMessage(Enum.class, (e) -> "can't find enum " + e)
            .interceptExceptionWithMessage(IllegalStateException.class, (e) -> "can't find repository " + e)
            .interceptExceptionWithMessage(NullPointerException.class, (e) -> "name can't be null " + e)
            .invoke(); 


// This is the method im using on example above from RepositoryManager.class
RepositoryManager find(Types type, String name) {
     if (name == null)
         throw new NullPointerException();

     return VALUES.stream()
                  .filter(v -> v.getName.equals(name))
                  .findFirst()
                  .orElseThrow(() -> new IllegalStateException());
}

The example above will intercept the valueOf exception because there is no Types.NONE, but if it were valid it will check other exceptions, example: if the Types is valid but the name is null then it will intercept the NullPointerException throw, and interceptExceptionWithMessage also debugs to console with the custom message u put in it, example "can't find enum " or other... is possible make something like that, any ideas?





Aucun commentaire:

Enregistrer un commentaire