How to Implement a Unified Response Format and Global Exception Handling in SpringBoot

This tutorial explains why a consistent response wrapper is needed in SpringBoot, shows how to define a standard JSON format with status, message and data fields, and demonstrates using ResponseBodyAdvice and a global exception handler to automatically wrap successful and error results.

macrozheng
macrozheng
macrozheng
How to Implement a Unified Response Format and Global Exception Handling in SpringBoot

Today we discuss how to return a friendly unified standard format and elegantly handle global exceptions in a SpringBoot front‑back separation project.

Why unify SpringBoot response format

By default SpringBoot can return three kinds of data: a plain String, a custom object, or an exception JSON. Without a consistent wrapper front‑end developers struggle to parse responses.

Define the standard response format

The wrapper should contain three fields: status (custom status code), message (description), and data (payload). Additional fields such as timestamp can be added.

{
  "status":"100",
  "message":"Operation successful",
  "data":"hello,javadaily"
}

ResultData class

@Data
public class ResultData<T> {
    private int status;
    private String message;
    private T data;
    private long timestamp;
    public ResultData() { this.timestamp = System.currentTimeMillis(); }
    public static <T> ResultData<T> success(T data) { /* ... */ }
    public static <T> ResultData<T> fail(int code, String message) { /* ... */ }
}

ReturnCode enum

public enum ReturnCode {
    RC100(100,"Operation successful"),
    RC500(500,"System error"),
    // other codes …
    private final int code;
    private final String message;
    // getters …
}

Automatic wrapping with ResponseBodyAdvice

Implement a ResponseBodyAdvice bean to intercept all controller return values and wrap them with ResultData.success(). For String results, convert the wrapper to JSON manually.

@RestControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired ObjectMapper objectMapper;
    public boolean supports(...) { return true; }
    public Object beforeBodyWrite(Object o, ...) {
        if (o instanceof String) {
            return objectMapper.writeValueAsString(ResultData.success(o));
        }
        return ResultData.success(o);
    }
}

Why SpringBoot needs a global exception handler

Global exception handling removes the need for repetitive try‑catch blocks and allows custom exceptions and validation errors to be transformed into the unified format.

Global exception handler

@RestControllerAdvice
public class RestExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResultData<String> exception(Exception e) {
        log.error("Global exception", e);
        return ResultData.fail(ReturnCode.RC500.getCode(), e.getMessage());
    }
}

When both ResponseAdvice and RestExceptionHandler are active, the advice may wrap the already‑wrapped error response. Adding a check for instanceof ResultData prevents double wrapping.

if (o instanceof ResultData) {
    return o;
}
return ResultData.success(o);

After this adjustment, error endpoints return a clean JSON with the proper status, message, data, and timestamp.

Unified response illustration
Unified response illustration
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpringBootresponsebodyadviceGlobalExceptionHandlingStandardResponse
macrozheng
Written by

macrozheng

Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.