title: How to wrap an OAuth2 exception?
body: <p>We have a rest API that uses <code>Spring OAuth2</code>. After the user is authenticated, all the JSON responses are in the following format:</p>
  
  <pre><code>{"code" : 12345, "data" : "..." }
  </code></pre>
  
  <p>But the JSON response for authentication failures is not inline with the above format, as that is handled by Spring. </p>
  
  <p>For example in case of incorrect credentials, the clients get
  HTTP status code 400 with JSON response as follows:</p>
  
  <pre><code>{"error": "invalid_grant", "error_description": "Bad credentials" }
  </code></pre>
  
  <p>In case the user account is locked, the clients get HTTP status code 400 with JSON response as follows</p>
  
  <pre><code>{"error":"invalid_grant","error_description":"User account is locked"}
  </code></pre>
  
  <p>All of this is because Spring TokenEndpoint.handleException() is handling the exceptions associated with /oauth/token</p>
  
  <p>I would like to change the JSON response for OAuth2 failures to follow the first format.</p>
  
  <p>This is what I have tried so far with no success:</p>
  
  <ol>
  <li>Use ControllerAdvice with highest precendence order &amp; use @ExceptionHandler as described <a href="https://stackoverflow.com/questions/19498378/setting-precedence-of-multiple-controlleradvice-exceptionhandlers/20473464#20473464">here</a></li>
  <li>implementing OAuth2ExceptionRenderer as described <a href="https://stackoverflow.com/questions/15110734/customize-springsecurity-oauth-2-error-output-unauthorized/15882640#15882640">here</a></li>
  <li>implement ExceptionMapper</li>
  <li>added a new ObjectMapper with extending StdSerializer. Although my objectmapper is initialized it is not being used for serializing the exceptions. Maybe because Spring is calling MappingJackson2HttpMessageConverter directly and there seems to be several instances of this class in my app.</li>
  </ol>
  
  <p>Any help in any of the above approaches or a new one would be highly appreciated.</p>
  
  <p>I haven't tried <a href="https://stackoverflow.com/questions/31154557/customise-oath2-token-request-to-accept-extra-data/31183131#31183131">this</a> approach as I cannot change the contextpath for the existing clients.</p>