Kumar V
Kumar V

Reputation: 1670

Spring Exception handler - Handling multiple exceptions

Below is my ExceptionHandler method to handle different exceptions that can be thrown from service class.

@ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handle(ExceptionA e) {
    log.error("Exception occurred: {} {}", e.getMessage(), e);
}

When ExceptionA is thrown, everything works as expected. But when ExceptionB is thrown, it gives the error No suitable resolver for argument 0 of type 'ExceptionA'. I guess its because the method argument for handle method is Exception A (still I would expect the error message should say No resolver for Exception B).

What should be the method argument for handle method so that it can handle any of the 3 exceptions?

Note: All Exceptions are created by extending from RuntimeException.

Upvotes: 3

Views: 3587

Answers (2)

Suraj
Suraj

Reputation: 767

Make your own base class extending RuntimeException

public class HandledRuntimeException extends RuntimeException{
}

and extend this class from your exception class like,

public class ExceptionA extends HandledRuntimeException{
}

and finally, in your handle method, you can change as below

@ExceptionHandler({HandledRuntimeException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handle(HandledRuntimeException e) {
    log.error("Exception occurred: {} {}", e.getMessage(), e);
}

Upvotes: 1

Puce
Puce

Reputation: 38152

You need a common base class as parameter type, e.g RuntimeException:

@ExceptionHandler({ExceptionA.class, ExceptionB.class, ExceptionC.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public void handle(RuntimeException e) {
    log.error(e.getMessage(), e);
}

Upvotes: 3

Related Questions