0
0
SpringbootHow-ToBeginner · 3 min read

How to Return Error Response in Spring Boot: Simple Guide

In Spring Boot, you can return an error response by using ResponseEntity with an appropriate HTTP status and message body. Alternatively, use @ExceptionHandler in a controller or @ControllerAdvice class to handle exceptions and send custom error responses.
📐

Syntax

Use ResponseEntity<T> to return a response with a status code and body. The key parts are:

  • body: The error message or object to send.
  • HttpStatus: The HTTP status code like BAD_REQUEST or NOT_FOUND.

Example syntax:

java
return new ResponseEntity<>("Error message", HttpStatus.BAD_REQUEST);
💻

Example

This example shows a REST controller that returns a 400 Bad Request error with a message when a condition fails.

java
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

    @GetMapping("/check")
    public ResponseEntity<String> checkValue(@RequestParam int value) {
        if (value < 0) {
            return new ResponseEntity<>("Value must be non-negative", HttpStatus.BAD_REQUEST);
        }
        return new ResponseEntity<>("Value is valid", HttpStatus.OK);
    }
}
Output
HTTP 400 Bad Request Body: "Value must be non-negative"
⚠️

Common Pitfalls

Common mistakes include:

  • Not setting the HTTP status code, which defaults to 200 OK even on errors.
  • Returning plain strings without ResponseEntity, losing control over status codes.
  • Not handling exceptions globally, leading to unclear error messages.

Use @ExceptionHandler or @ControllerAdvice to centralize error handling.

java
/* Wrong way: returns 200 OK even on error */
@GetMapping("/wrong")
public String wrongError() {
    return "Error happened";
}

/* Right way: returns 400 Bad Request with message */
@GetMapping("/right")
public ResponseEntity<String> rightError() {
    return new ResponseEntity<>("Error happened", HttpStatus.BAD_REQUEST);
}
📊

Quick Reference

Tips for returning error responses in Spring Boot:

  • Use ResponseEntity to set status and body explicitly.
  • Use @ExceptionHandler methods to catch exceptions and return custom errors.
  • Use @ControllerAdvice to handle errors globally across controllers.
  • Return meaningful messages and proper HTTP status codes for better API clarity.

Key Takeaways

Use ResponseEntity to return error messages with proper HTTP status codes.
Handle exceptions with @ExceptionHandler or @ControllerAdvice for clean error responses.
Always set the correct HTTP status to avoid confusing clients.
Return clear and meaningful error messages in the response body.
Centralize error handling to keep controllers simple and consistent.