title: Spring Boot Returning 401 Statused Custom Object From Exception Handler
body: <p>I have an Spring Boot rest API that have an LoginController for doing simple authentication processes. This is the token validation action.</p>
  
  <pre><code>@PostMapping("validatetoken")
  public ResponseEntity&lt;ValidateTokenResponse&gt; validateToken(
          @RequestBody ValidateTokenRequest validateTokenRequest, HttpServletRequest request) throws Exception {
  
      if (StringUtils.isEmpty(validateTokenRequest.getToken())) throw new AuthenticationFailedException("token parameter cannot be null or empty");
  
      Boolean isValid = authenticationService.validateToken(request, validateTokenRequest.getToken());
      ValidateTokenResponse response = new ValidateTokenResponse();
      response.setIsValid(isValid);
      response.setToken(validateTokenRequest.getToken());
      return new ResponseEntity&lt;&gt;(response, isValid? HttpStatus.OK : HttpStatus.UNAUTHORIZED);
  }
  </code></pre>
  
  <p>And in my api I'm catching all errors in a <code>ResponseEntityExceptionHandler</code> and converting a custom object this way.</p>
  
  <pre><code>@ExceptionHandler(AuthenticationFailedException.class)
  @ResponseBody
  protected ResponseEntity&lt;Object&gt; handleAuthenticationFailed(AuthenticationFailedException ex) {
      LogManager.error(ex);
      ApiError apiError = new ApiError(HttpStatus.UNAUTHORIZED);
      apiError.setMessage(ex.getMessage());
      return buildResponseEntity(apiError);
  }
  </code></pre>
  
  <p>But when I want to call this api using <code>RestTemplate</code> like below I'm getting and exception like <em>java.net.HttpRetryException: cannot retry due to server authentication, in streaming mode</em>. </p>
  
  <pre><code>ResponseEntity&lt;String&gt; responseEntity =
      restTemplate.exchange(
          this.validateTokenUrl,
          HttpMethod.POST,
          requestHttpEntity,
          String.class);
  </code></pre>
  
  <p>But if I change <code>HttpStatus</code> from <code>ExceptionHandler</code> to except <code>HttpStatus.UNAUTHORIZED</code> I can get true <code>ApiError</code> object from the client. What can cause this problem and how can I resolve it?</p>
  
  <p>EDIT: Created a <a href="https://github.com/yusufduyar/question-sample" rel="nofollow noreferrer">github repo</a> that mimics my problemic parts of my project.</p>