Set appropriate Status Codes on HTTP responses

  • What language are you writing rules for?

Java 21 / IntelliJ 2024.1.1 / Sonarlint 10.6.2.78685

  • What have you tried, and what’s your challenge / stumbling block

java:S6863 rule “Set appropriate Status Codes on HTTP responses”

My linter tels me that the following code is not compliant and that I have low impact on reliability:

        try {
            return service.update(someStuff)
                    .map(ResponseEntity::ok)
                    .orElse(ResponseEntity.notFound().build());
        } catch (Exception e) {
            log.error("Error updating stuff with id {}: {}", stuffId, e.getMessage());
            return ResponseEntity.internalServerError().build();
        }

The issue comes from the line .orElse(ResponseEntity.notFound().build()).

Now, the java rule java:S6863 as is described in the Linter, in the “how to fix it” section sais that the compliant code looks like this:

        try {
            User user = userService.getUserById(userId);
            return ResponseEntity.ok(user); // Compliant: Setting 200 for a successful operation
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); // Compliant: Setting 500 for exception
        }

I do believe that my code is compliant because service return an Optional. if object someStuff has not been found, the returned Optional is empty and return a 404, which is more acurate than a generic 500.

Is their something I’m missing here? Or could it be a false positive?

1 Like

Thank you, @AviEL, for reporting this false positive.

You can track the progress on the fix at [SONARJAVA-5092] - Jira.

Cheers,
Angelo

1 Like

Hey Angelo,

THX for taking my issue into account.

I stumbled on this same issue again, and now I noticed that issue does not appear until I annotated my class with @RestController.

So now it appears that I need to give you a bit more context: I’m building a web application using SpringBoot 3.3.1.

Therefore the FP only araises in a @RestController context. For simple POJOs with decoration, it seems to be all fine!

1 Like