I have an auto configure Spring Boot error page setup, as described in this answer. Currently I trigger the showing of error pages by throwing an exception, which works fine. But I'd like to not use Exceptions for control flow, so I'm looking for an alternative way. I also don't like that I have to create a new Exception, which is costly.
@GetMapping("/user/{id}")
public String showUser(@PathVariable Long id, Model model) {
Optional<Long> idOptional = userRepository.findOne(id);
if (idOptional.isEmpty()) {
throw new ResponseStatusException(HttpStatus.NOT_FOUND);
}
// do stuff
return "user/index";
}
I know I can use the HttpServletResponse to set the status but then I bypass the Spring Boot error page handling and have to render the template myself, so I have to add the model attributes myself:
@GetMapping("/user/{id}")
public String showUser(@PathVariable Long id, Model model, HttpServletResponse response) {
Optional<Long> idOptional = userRepository.findOne(id);
if (idOptional.isEmpty()) {
response.setStatus(404);
model.addAttribute("status", 404);
return "error";
}
// do stuff
return "user/index";
}
Is there a way of to use the custom error page support (not specifying and preparing the template myself) without throwing an Exception?