Home > Mobile >  Java exception handler for class
Java exception handler for class

Time:05-27

Is it possible to have a uniform exception handler for all instance methods of a class in Java? For example, if I have the class Car:

class Car {
  public void drive(double miles) {
     ...
  }

  public void turnLeft() {
    ...
  }
  
  public void turnRight() {
    ...
  }
}

Could I add a handler function that is called every time an exception is thrown by one of these methods? The ultimate goal would be to log all of these exceptions in a uniform way, even if they are ultimately caught and ignored by higher levels of the stack.

CodePudding user response:

If you are using spring , then you can catch all exceptions in one class https://www.baeldung.com/exception-handling-for-rest-with-spring Using an ExceptionMapper class.

If it is a normal app, in your public static void main you can surround your code in try catch to catch all exceptions.

CodePudding user response:

Extend a Proxy to delegate Car. We can use jdk Proxy if car has a interface, or use cglib. Just like what some framework(Spring...) has provided. Code below is a example of cglib.

class ErrorHandleProxy implements MethodInterceptor {
    public Object createProxy(Object target) {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        enhancer.setClassLoader(target.getClass().getClassLoader());
        return enhancer.create();
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        Object ret = null;
        try {
            ret = proxy.invokeSuper(obj, args);
        } catch (Exception e) {
            /// do logging or rethrow exception
        }
        return ret;
    }
}

And then, we can call car with this Proxy

Car car = new Car();
Car proxy = (Car)new ErrorHandleProxy().createProxy(car);
proxy.xxx
  • Related