title: Using Spring MVC, accepting POST requests with bad JSON leads to a default 400 error code server page being returned
body: <p>I am working on a REST api.  Receiving a POST message with bad JSON (e.g. { sdfasdfasdf } ) causes Spring to return the default server page for a 400 Bad Request Error.  I do not want to return a page, I want to return a custom JSON Error object.</p>
  
  <p>I can do this when there is an exception thrown by using an @ExceptionHandler.  So if it is a blank request or a blank JSON object (e.g. { } ), it will throw a NullPointerException and I can catch it with my ExceptionHandler and do whatever I please.</p>
  
  <p>The problem then, is that Spring doesn't actually throw an exception when it is just invalid syntax... at least not that I can see.  It simply returns the default error page from the server, whether it is Tomcat, Glassfish, etc.</p>
  
  <p>So my question is how can I "intercept" Spring and cause it to use my exception handler or otherwise prevent the error page from displaying and instead return a JSON error object?</p>
  
  <p>Here is my code:</p>
  
  <pre><code>@RequestMapping(value = "/trackingNumbers", method = RequestMethod.POST, consumes = "application/json")
  @ResponseBody
  public ResponseEntity&lt;String&gt; setTrackingNumber(@RequestBody TrackingNumber trackingNumber) {
  
      HttpStatus status = null;
      ResponseStatus responseStatus = null;
      String result = null;
      ObjectMapper mapper = new ObjectMapper();
  
      trackingNumbersService.setTrackingNumber(trackingNumber);
      status = HttpStatus.CREATED;
      result = trackingNumber.getCompany();
  
  
      ResponseEntity&lt;String&gt; response = new ResponseEntity&lt;String&gt;(result, status);
  
      return response;    
  }
  
  @ExceptionHandler({NullPointerException.class, EOFException.class})
  @ResponseBody
  public ResponseEntity&lt;String&gt; resolveException()
  {
      HttpStatus status = null;
      ResponseStatus responseStatus = null;
      String result = null;
      ObjectMapper mapper = new ObjectMapper();
  
      responseStatus = new ResponseStatus("400", "That is not a valid form for a TrackingNumber object " + 
              "({\"company\":\"EXAMPLE\",\"pro_bill_id\":\"EXAMPLE123\",\"tracking_num\":\"EXAMPLE123\"})");
      status = HttpStatus.BAD_REQUEST;
  
      try {
          result = mapper.writeValueAsString(responseStatus);
      } catch (IOException e1) {
          e1.printStackTrace();
      }
  
      ResponseEntity&lt;String&gt; response = new ResponseEntity&lt;String&gt;(result, status);
  
      return response;
  }
  </code></pre>