Hackforge Academy

Category: React • Beginner

Published on 11 Apr 2026

Explanation

Use ResponseEntity to send custom HTTP status codes along with response body. This is the most flexible and commonly used approach in Spring Boot APIs.

Code Example

@GetMapping("/success")
public ResponseEntity<String> 
successExample() {
    return ResponseEntity.status(
HttpStatus.OK).body("Request successful");
}

Explanation

Use ResponseEntity helper methods like ok(), badRequest(), and notFound() for cleaner and shorter syntax while returning standard HTTP status codes.

Code Example

@GetMapping("/shortcut")
public ResponseEntity<String> 
shortcutExample() {
    return ResponseEntity.badRequest().
body("Invalid request data");
}

Explanation

Use @ResponseStatus annotation on controller methods to return a fixed HTTP status code automatically without ResponseEntity.

Code Example

@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/create")
public String createResource() {
    return "Resource created successfully";
}

Explanation

Use ResponseStatusException when you want to throw an exception with a specific HTTP status dynamically inside a method.

Code Example

@GetMapping("/error")
public String errorExample() {
    throw new ResponseStatusException(
HttpStatus.NOT_FOUND, "Resource not found");
}

Explanation

Use @ExceptionHandler inside a controller to handle specific exceptions and return custom status codes.

Code Example

@ExceptionHandler(RuntimeException.class)
@ResponseStatus(HttpStatus.
INTERNAL_SERVER_ERROR)
public String handleRuntimeException(
RuntimeException ex) {
    return ex.getMessage();
}

Explanation

Use @RestControllerAdvice for global exception handling across the application and return structured responses with custom status codes.

Code Example

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> 
handleGlobalException(Exception ex) {
        return ResponseEntity.status(
HttpStatus.INTERNAL_SERVER_ERROR)
                             .body("
Something went wrong");
    }
}

Want structured learning with real projects?

Join our Weekend Live Workshop and become job-ready faster.