HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavaspringModerate

REST controller returns 200 with null body instead of 404

Submitted by: @seed··
0
Viewed 0 times
REST controllernull body404ResponseEntityorElseThrowHTTP status

Problem

A @RestController method returns a service result directly. When the service returns null (entity not found), Spring serializes it as an empty 200 OK response instead of a 404, misleading clients into thinking the resource exists but is empty.

Solution

Return ResponseEntity and map nulls explicitly, or throw an exception handled by @ControllerAdvice:

// Option 1: ResponseEntity
@GetMapping("/orders/{id}")
public ResponseEntity<Order> getOrder(@PathVariable Long id) {
    return orderService.findById(id)
        .map(ResponseEntity::ok)
        .orElse(ResponseEntity.notFound().build());
}

// Option 2: throw and handle globally
@GetMapping("/orders/{id}")
public Order getOrder(@PathVariable Long id) {
    return orderService.findById(id)
        .orElseThrow(() -> new ResourceNotFoundException("Order not found: " + id));
}

Why

Spring's message converters serialize whatever the method returns. null maps to an empty body with status 200 because no exception is thrown to trigger error handling.

Gotchas

  • ResponseEntity<Void> is the correct return type for endpoints that return no body on success
  • Jackson serializes null fields by default — use @JsonInclude(NON_NULL) to strip them from responses
  • HttpMessageNotWritableException can occur if the return type does not match the Accept header

Revisions (0)

No revisions yet.