Why this matters
Returning incorrect HTTP status codes can lead to ambiguous API behavior, making it harder for clients to handle responses correctly.
Ensure that HTTP handlers return the appropriate status codes based on request success or failure.
Returning incorrect HTTP status codes can lead to ambiguous API behavior, making it harder for clients to handle responses correctly.
Side-by-side examples engineers can pattern-match during review.
@Controller
public class UserController {
public ResponseEntity<User> getUserById(Long userId) {
try {
User user = userService.getUserById(userId);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(user); // Noncompliant: Setting 500 for a successful operation
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.OK).build(); // Noncompliant: Setting 200 for exception
}
}
}@Controller
public class UserController {
public ResponseEntity<User> getUserById(Long userId) {
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
}
}
}@Controller
public class UserController {
public ResponseEntity<User> getUserById(Long userId) {
try {
User user = userService.getUserById(userId);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(user); // Noncompliant: Setting 500 for a successful operation
} catch (Exception e) {
return ResponseEntity.status(HttpStatus.OK).build(); // Noncompliant: Setting 200 for exception
}
}
}@Controller
public class UserController {
public ResponseEntity<User> getUserById(Long userId) {
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
}
}
}From the same buckets as this rule.