How to Configure Global Exceptions and Response Objects in Spring Boot
This guide shows how to create a unified ApiResult response class, define a custom BaseException, and set up a @RestControllerAdvice handler in Spring Boot to centralize error handling and return consistent response payloads.
To achieve a clear and uniform way of returning information in a Spring Boot project, the article first defines a response wrapper class ApiResult. The class implements Serializable and contains a result code, a message, and a data map. Several constructors allow initializing these fields with default success values from ApiResponse or with custom values.
public class ApiResult implements Serializable {
/** 响应码 */
private String resultCode;
/** 响应描述 */
public String msg;
/** 返回数据对象 */
public Map data = new HashMap<>();
public ApiResult() {
this.resultCode = ApiResponse.SUCCESS.getResCode();
this.msg = ApiResponse.SUCCESS.getResDesc();
}
public ApiResult(Map data) {
this.resultCode = ApiResponse.SUCCESS.getResCode();
this.msg = ApiResponse.SUCCESS.getResDesc();
this.data = data;
}
public ApiResult(ApiResponse resp, Map data) {
this.resultCode = resp.getResCode();
this.msg = resp.getResDesc();
this.data = data;
}
public ApiResult(ApiResponse resp, Map data, String msg) {
this.resultCode = resp.getResCode();
this.msg = msg;
this.data = data;
}
}Next, a custom exception class BaseException is introduced to encapsulate an ApiResponse object. It provides constructors for wrapping a cause or a message, allowing the exception to carry detailed response information.
public class BaseException extends Exception {
/** 响应完整信息 */
private ApiResponse response;
public BaseException(Throwable cause) {
super(cause);
}
public BaseException(String message) {
super(message);
}
}After defining the exception, the article configures a global exception handler using @RestControllerAdvice. The handler class TyBusExceptionHandler logs the error and builds an ApiResult based on the ApiResponse contained in the caught BaseException. If the response message is empty, the handler uses the exception's message; otherwise, it returns the response without a custom message.
@RestControllerAdvice
public class TyBusExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@ExceptionHandler(BaseException.class)
@ResponseBody
public ApiResult handle(BaseException e) {
logger.error("错误信息是:{}", e);
ApiResult resp = null;
ApiResponse response = e.getResponse();
if (response == null || StringUtils.isEmpty(response.getReturnMsg())) {
resp = new ApiResult(e.getResponse(), null, e.getMessage());
} else {
resp = new ApiResult(e.getResponse(), null);
}
return resp;
}
}With these components— ApiResult, BaseException, and the TyBusExceptionHandler —the project now has a complete global exception handling mechanism that returns consistent response structures for all errors.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Coder Trainee
Experienced in Java and Python, we share and learn together. For submissions or collaborations, DM us.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
