I\'m looking for a clean way to return customized 404 errorpages in Spring 4 when a requested resource was not found. Queries to different domain types should result in diff
The solution is much simpler than thought. One can use one generic ResourceNotFoundException defined as follows:
public class ResourceNotFoundException extends RuntimeException { }
then one can handle errors within every controller with an ExceptionHandler annotation:
class MeterController {
// ...
@ExceptionHandler(ResourceNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleResourceNotFoundException() {
return "meters/notfound";
}
// ...
@RequestMapping(value = "/{number}/edit", method = RequestMethod.GET)
public String viewEdit(@PathVariable("number") final Meter meter,
final Model model) {
if (meter == null) throw new ResourceNotFoundException();
model.addAttribute("meter", meter);
return "meters/edit";
}
}
Every controller can define its own ExceptionHandler for the ResourceNotFoundException.