'How to override a method of an external library?

I want to suppress the stacktrace of a specific exception: org.everit.json.schema.ValidationException.

This particular exception is thrown a lot in our application, and I want to limit the performance hit.

I tried extending it with my own:

public class SuppressValidationException extends ValidationException {

  public SuppressEveritValidationException(Schema violatedSchema,
      Class<?> expectedType, Object actualValue) {
    super(violatedSchema, expectedType, actualValue);
  }

  public SuppressEveritValidationException(Schema violatedSchema, Class<?> expectedType,
      Object actualValue, String keyword) {
    super(violatedSchema, expectedType, actualValue, keyword);
  }

  @Override
  public Throwable fillInStackTrace() {
    return this;
  }
}

But when I catch the SuppressValidation, the ValidationException goes uncaught. Is there a way to achieve what I am trying to do?



Solution 1:[1]

You could write a simple wrapper around the class of this external library that actually throws this exception, just pass through any method calls to the one with the same name, and catch exceptions if appropriate and rethrow a simpler version.

Also, whether you actually log the stacktrace will also depend on your logging framework and it can probably also be configured to not do that.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sebastiaan van den Broek