I am using ControllerAdvice to handle exceptions in my spring boot application.
@Order(Ordered.HIGHEST_PRECEDENCE)
@ControllerAdvice
public class ErrorApiHandler extends ResponseEntityExceptionHandler {
final
ResponsesHelper rh;
public ErrorApiHandler(ResponsesHelper rh) {
this.rh = rh;
}
@ExceptionHandler(UsernameNotFoundException.class)
public ResponseEntity<Object> handleUsernameNotFoundException(UsernameNotFoundException ex) {
log.error(ExceptionUtils.getStackTrace(ex));
var error = buildError(ex);
return rh.buildResponse(error, HttpStatus.NOT_FOUND);
}
...
}
It works fine for exceptions thrown within my controllers. However, with exceptions thrown, for example within a service the ControllerAdvice is not executed.
@Service
public class CustomUserDetailsService implements UserDetailsService {
final
UserRepository userRepository;
public CustomUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
@Transactional
public User loadUserByUsername(String email)
throws UsernameNotFoundException {
log.debug(String.format("Loading user %s", email));
User user = userRepository.findByEmail(email)
.orElseThrow(() -> {
log.debug(String.format("User %s not found", email));
return new UsernameNotFoundException("User not found : " + email); // <- This exception is not handled.
});
log.debug(String.format("User %s loaded", user));
return user;
}
How can I handle all exceptions thrown within my application?
Thanks in advance.