How to standardize response format in SpringBoot?

With Spring Boot, you can achieve a uniform response format by customizing a global exception handler and result wrapping class.

  1. @ControllerAdvice is used in Spring framework to handle exceptions globally in all controllers.
  2. Handler for exceptions

The sample code is shown below:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result handleException(Exception e) {
        // 处理异常逻辑,可以根据不同的异常类型返回不同的错误码和错误信息
        return Result.error(500, e.getMessage());
    }
}
  1. Return Result Encapsulation Class:
    Create a class to encapsulate the format of the return result, including status code and message content, and other information.

The sample code is shown below:

public class Result<T> {

    private int code;
    private String message;
    private T data;

    // getter和setter方法

    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.setCode(200);
        result.setMessage("操作成功");
        result.setData(data);
        return result;
    }

    public static <T> Result<T> error(int code, String message) {
        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        return result;
    }
}

After configuration is complete, the global exception handler will handle any exceptions that occur and return custom error codes and messages. In normal cases, a successful response can be returned using the Result.success() method, where the data parameter is the data that needs to be returned. This way, a unified response format can be achieved.

bannerAds