0

How do we access the HTTP status code that we have already returned in the finally block.

For example, in the below snippet, how can we get returned HTTP status code in logResponseStatus?


public ResponseEntity<SampleResponse> sampleAPI() {
    try{
        return new ResponseEntity<>(new SampleResponse(), HttpStatus.OK);
    } finally {
        logResponseStatus();
    }
}

void logResponseStatus(HttpStatus status) {
    // ...
}
Kumar Nitin
  • 1,845
  • 2
  • 16
  • 21
  • 2
    I assume that this is a SpringBoot app. In that case you can add filters and log the response status/body in the filters. I would recommend going through this link as it has multiple answers with different ways of doing the same: https://stackoverflow.com/questions/33744875/spring-boot-how-to-log-all-requests-and-responses-with-exceptions-in-single-pl – Vishal Sep 04 '20 at 00:13
  • @Vishal Using Aspect would've been a clean way of handling it. But we can't use annotations since we will also be sending dynamic tags along with HTTP status here. – Kumar Nitin Sep 04 '20 at 00:21
  • You should use a Filter or AOP. Based on your snippet, I would say put the return code in a variable then pass in argument to logResponseStatus... – Cyril G. Sep 04 '20 at 00:24

0 Answers0