title: Spring Boot Controller Advice - How to return XML instead of JSON?
body: <p>I have a controller advice class, but I can't seem to get it to return XML, even though I've used the <code>@RequestMapping</code> annotation. Here's a stripped-down example.</p>
  <pre class="lang-java prettyprint-override"><code>@RestControllerAdvice
  public class ControllerAdvice {    
      @ExceptionHandler(Exception.class)
      @RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)
      public PriceAvailabilityResponse handleControllerErrorXML(final Exception e) {
          e.printStackTrace();
          System.out.println(&quot;Exception Handler functional&quot;);
      
          PriceAvailabilityResponse priceAvailabilityResponse = new PriceAvailabilityResponse();
          priceAvailabilityResponse.setStatusMessage(&quot;Server Error&quot;);
          priceAvailabilityResponse.setStatusCode(99);
          
          return priceAvailabilityResponse;
      }
  }
  </code></pre>
  <p>Note how <code>@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE)</code> works in rest controllers to control how the response is formed.</p>
  <p>And here's an example of what the <code>PriceAvailabilityResponse</code> could be from the aforementioned block of code.</p>
  <pre class="lang-java prettyprint-override"><code>@XmlRootElement
  @XmlAccessorType(XmlAccessType.FIELD)
  @JsonInclude(JsonInclude.Include.NON_EMPTY)
  @Getter
  @Setter
  public class PriceAvailabilityResponse {
      @JacksonXmlProperty(isAttribute = true, localName = &quot;StatusCode&quot;)
      @JsonProperty(value = &quot;StatusCode&quot;, required = false)
      private int statusCode = 0;
  
      @JacksonXmlProperty(isAttribute = true, localName = &quot;StatusMessage&quot;)
      @JsonProperty(value = &quot;StatusMessage&quot;, required = false)
      private String statusMessage;
  }
  </code></pre>
  <p>And below is an example rest controller method to throw the error</p>
  <pre class="lang-java prettyprint-override"><code>@RequestMapping(value = &quot;/error_test&quot;, produces = MediaType.APPLICATION_XML_VALUE)
  public PriceAvailabilityResponse getPriceResponse() throws Exception{
      int x = 1/0;
      return null;
  }
  </code></pre>
  <p>I've written the model for this code to return both JSON and XML depending on which endpoint is hitting the microservice, that is absolutely imperative.</p>
  <p>Unfortunately, when I hit the <code>/error_test</code> path, my response always comes in JSON.</p>
  <p><a href="https://i.stack.imgur.com/hS5le.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hS5le.png" alt="enter image description here" /></a></p>
  <p>How could I force the response to be XML? Thanks so much for your time.</p>