title: How do I prevent browser caching in Spring MVC when an Exception occurs?
body: <p>I want to make the browser cache my responses, but only in case the return status is 200.</p>
  
  <p>I know how to enable cache-control header in Spring MVC. However, when my code throws an exception that is handled by an <em>Exceptionhandler</em> that returns a HTTP error status (e.g. 404) then the response header still has the cache-control which makes the browser cache the response. This is not the desired behavior. When my code returns a HTTP error status I do <strong>not</strong> want that response to be cached by the browser.</p>
  
  <p>I have tried writing my own <em>HandlerInterceptor</em> that sets the cache-control header in the <em>postHandle</em> or <em>afterCompletion</em> methods. However I see that these methods do not get invoked, or get invoked after the response is sent to the browser.</p>
  
  <p>I use Spring 4.1.6. My controller is a <em>RestController</em> that returns a <em>ResponseEntity</em>. It does <strong>not</strong> return a view that is then processed by a <em>ViewResolver</em>.</p>