I would like to know whether relying on custom exception types for flow control is considered good practice.
Let's take an example:
public void activateEmail(String token) {
Member member = memberRepository.findByToken(token);
if (member == null) {
throw new InvalidTokenException("Member not found");
}
...
Here, InvalidTokenException
is a custom RuntimeException
that is thrown if an entity is not found in database.
I use a Spring MVC exception handler as follows in order to deal with my custom exception:
@ExceptionHandler(InvalidTokenException.class)
public String invalidTokenException(InvalidTokenException e, HttpServletRequest request, HttpSession session, Locale locale) {
FlashMap outputFlashMap = RequestContextUtils.getOutputFlashMap(request);
if (outputFlashMap != null) {
outputFlashMap.put("message", messageSource.getMessage("controller.preference.invalid_token_member_not_found", null, locale));
}
return "redirect:/signin";
}
What are the pros and cons of such a usage of my custom exceptions?