Home > Software engineering >  How to add an Exception Handler for an exception type that could be custom or default
How to add an Exception Handler for an exception type that could be custom or default

Time:01-10

I have a use case where for certain exception's that are normally thrown by a web framework that I can override the value by using my own MyCustomException object.

@ExceptionHandler({SomeWebFrameworkException.class})
public ResponseEntity<Object> handleException(MyCustomException exception) { ... }

However, if I want an exception handler to be able to be able to accept my custom exception then, I would need to cover all cases of this web framework error being thrown. Is there a way to somehow make it accept MyCustomException as input otherwise just default to a normal Exception ? If I just use a simple Exception as the input then, it would end up getting treated as the SomeWebFrameworkException instead of my own.

@ExceptionHandler({SomeWebFrameworkException.class})
public ResponseEntity<Object> handleException(Exception exception1, MyCustomException exception2) { ... }

CodePudding user response:

You can have multiple exception handling methods defined, similarly to catch-blocks

@ExceptionHandler(MyCustomException.class)
public ResponseEntity<Object> handleMyCustomException(MyCustomException exception) { ... }

@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleGenericException(Exception exception) { ... }
  • Related