I would like to add an Elapsed-Time response header parameter on every API REST request, even those that finish with error.
For instance:
===>
GET /api/customer/123 HTTP/1.1
Accept: application/vnd.company.app.customer-v1+json
<===
HTTP/1.1 200 OK
Content-Type: application/vnd.company.app.customer-v1+json
Elapsed-Time: 12
{ id: 123, name: Jordi, age: 28 }
Being Elapsed-Time parameter calculated as the difference in milliseconds between the instant that the @RequestMapping method finishes, and the instant that the @RequestMapping method starts.
I have been taking a look on Spring4 HandlerInterceptorAdapter. preHandle and postHandle methods seem to fit perfectly for this case (despite the time overhead of executing every interceptor in the chain). But, unfortunatelly, changing response header in postHandle method has no effect because the response is already build.
Spring documentation states:
Note that the postHandle method of HandlerInterceptor is not always ideally suited for use with @ResponseBody and ResponseEntity methods. In such cases an HttpMessageConverter writes to and commits the response before postHandle is called which makes it impossible to change the response, for example to add a header. Instead an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter.
Do you know of any working elegant solution to deal with this case?
I don't think think this case is duplicating Spring - Modifying headers for every request after processing (in postHandle) because I need to capture a variable whose value is the start time (when petition gets to the application and before the @RequestMapping method starts), and then use this variable once the @RequestMapping method finishes, to compute the elapsed time.