Hackforge Academy

Category: java

Custom HTTP status in spring boot

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:

@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:

@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:

@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:

@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:

@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:

@RestControllerAdvice
public class GlobalExceptionHandler {

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

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community