title: Spring MVC: How to return custom 404 errorpages?
body: <p>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 different error pages.</p>
  
  <p>Here some code to show my intention (Meter is a domain class):
  </p>
  
  <pre><code>@RequestMapping(value = "/{number}", method = RequestMethod.GET)
  public String getMeterDetails(@PathVariable("number") final Long number, final Model model) {
      final Meter result = meterService.findOne(number);
      if (result == null) {
          // here some code to return an errorpage
      }
  
      model.addAttribute("meter", result);
      return "meters/details";
  }
  </code></pre>
  
  <p>I imagine several ways for handling the problem. First there would be the possibility to create <code>RuntimeException</code>s like
  </p>
  
  <pre><code>@ResponseStatus(HttpStatus.NOT_FOUND)
  public class MeterNotFoundExcption extends RuntimeException { }
  </code></pre>
  
  <p>and then use an exception handler to render a custom errorpage (maybe containing a link to a list of meters or whatever is appropriate).</p>
  
  <p>But I don't like polluting my application with many small exceptions.</p>
  
  <p>Another possibility would be using <code>HttpServletResponse</code> and set the statuscode manually:
  </p>
  
  <pre><code>@RequestMapping(value = "/{number}", method = RequestMethod.GET)
  public String getMeterDetails(@PathVariable("number") final Long number, final Model model,
  final HttpServletResponse response) {
      final Meter meter = meterService.findOne(number);
      if (meter == null) {
          response.setStatus(HttpStatus.NOT_FOUND.value());
          return "meters/notfound";
      }
  
      model.addAttribute("meter", meter);
      return "meters/details";
  }
  </code></pre>
  
  <p>But with this solution I have to duplicate the first 5 lines for many controller methods (like edit, delete).</p>
  
  <p>Is there an elegant way to prevent duplicating these lines many times?</p>