Backend Development 18 min read

Building a Robust Backend API with Spring Boot: Validation, Global Exception Handling, and Unified Response

This article demonstrates how to construct a well‑structured Spring Boot backend API by integrating request validation with Hibernate Validator, implementing global exception handling, defining custom exceptions, and standardizing responses using a unified response object and response‑body advice.

Top Architect
Top Architect
Top Architect
Building a Robust Backend API with Spring Boot: Validation, Global Exception Handling, and Unified Response

The article begins by outlining the four essential components of a backend interface—URL, request method, request data, and response data—and emphasizes the importance of a standardized API design.

It then introduces the required Maven dependency for Spring Boot web applications, showing the <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> snippet, and mentions optional tools such as Swagger and Lombok.

For parameter validation, the article first presents a manual validation approach in the service layer, illustrating verbose checks for null values, string length, and email format. It then recommends replacing this boilerplate with Hibernate Validator annotations, providing an example of a @Data public class User { @NotNull(message="用户id不能为空") private Long id; @NotNull(message="用户账号不能为空") @Size(min=6, max=11, message="账号长度必须是6-11个字符") private String account; @NotNull(message="用户密码不能为空") @Size(min=6, max=16, message="密码长度必须是6-16个字符") private String password; @NotNull(message="用户邮箱不能为空") @Email(message="邮箱格式不正确") private String email; } model.

The controller method is then simplified to @PostMapping("/addUser") public String addUser(@RequestBody @Valid User user, BindingResult bindingResult) { ... } , where validation errors are extracted from BindingResult and returned directly.

To further streamline validation, the article shows how to omit BindingResult entirely, letting Spring throw MethodArgumentNotValidException automatically. It demonstrates the resulting exception and the need for a global exception handler.

Global exception handling is introduced with a @RestControllerAdvice class that defines @ExceptionHandler(MethodArgumentNotValidException.class) and @ExceptionHandler(APIException.class) methods. The handlers return custom error messages extracted from the exception objects.

Custom exceptions are then defined, e.g., @Getter public class APIException extends RuntimeException { private int code; private String msg; ... } , allowing richer error information and centralized handling.

For response standardization, a generic ResultVO class is presented, containing code , msg , and data fields. Constructors are overloaded to accept a ResultCode enum, ensuring consistent status codes and messages.

The ResultCode enum defines values such as SUCCESS(1000,"操作成功") , FAILED(1001,"响应失败") , VALIDATE_FAILED(1002,"参数校验失败") , and ERROR(5000,"未知错误") .

To avoid wrapping each controller return manually, the article implements a ResponseBodyAdvice class annotated with @RestControllerAdvice(basePackages={"com.rudecrab.demo.controller"}) . Its supports method skips wrapping when the return type is already ResultVO , and its beforeBodyWrite method wraps any other return value in a ResultVO . Special handling for String responses converts the wrapped object to JSON using ObjectMapper .

Finally, the article shows how a simple controller method returning a User object is automatically transformed into a unified JSON response, and summarizes the benefits of the combined validation, exception handling, and response standardization approach.

exception handlingSpring BootAPI designParameter ValidationUnified Response
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.