Simplify Spring Boot API Development with Graceful Response
Graceful Response is a Spring Boot component that unifies response wrapping, global exception handling, and custom error codes, helping developers reduce boilerplate, improve readability, and accelerate API development while supporting validation and customizable response styles.
1. Introduction
Graceful Response is a Spring Boot component that provides a one‑stop solution for unified response wrapping, global exception handling, and custom error‑code mapping, allowing developers to save time and improve code quality.
Strongly recommend you spend 3 minutes to learn it!
Project example repository: https://github.com/feiniaojin/graceful-response-example.git (use the latest branch).
Spring Boot version
Graceful Response version
graceful-response-example branch
2.x
3.2.1-boot2
3.2.0-boot2
3.x
3.2.1-boot3
3.2.0-boot3
Note: the 3.2.1-boot2 version is maintained in a separate repository: https://github.com/feiniaojin/graceful-response-boot2 . The boot2 and boot3 implementations are identical except for the supported Spring Boot version; just choose the appropriate version in Maven.
2. Quick Start
2.1 Current situation of Spring Boot API development
Typical controller code contains repetitive boilerplate for parameter validation, result wrapping, and error handling, leading to low efficiency, duplicated work, and poor readability.
@Controller
public class Controller {
@GetMapping("/query")
@ResponseBody
public Response query(Map<String, Object> paramMap) {
Response res = new Response();
try {
// 1. validate params
if (illegal(paramMap)) {
res.setCode(1);
res.setMsg("error");
return res;
}
// 2. call service
Object data = service.query(params);
// 3. set result
res.setData(data);
res.setCode(0);
res.setMsg("ok");
return res;
} catch (Exception e) {
// 4. exception handling
res.setCode(1);
res.setMsg("error");
return res;
}
}
}Issues identified: low efficiency, duplicated labor, and low readability.
2.2 Quick Start
2.2.1 Add Maven dependency
Add the following dependency to your pom.xml:
<dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>{latest.version}</version>
</dependency>Spring Boot version
Graceful Response latest version
2.x
3.2.1-boot2
3.x
3.2.1-boot3
2.2.2 Enable Graceful Response
Annotate your Spring Boot application class with @EnableGracefulResponse:
@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}2.2.3 Controller layer
After enabling, controller methods can return plain objects; Graceful Response will automatically wrap them.
@Controller
public class Controller {
@RequestMapping("/get")
@ResponseBody
public UserInfoView get(Long id) {
log.info("id={}", id);
return UserInfoView.builder().id(id).name("name" + id).build();
}
}Result JSON example:
{
"status": {"code":"0","msg":"ok"},
"payload": {"id":1,"name":"name1"}
}For void command methods, a success response is also generated:
{
"status": {"code":"200","msg":"success"},
"payload": {}
}2.2.4 Service layer
Without Graceful Response, services often return custom Response objects, mixing business data with error codes:
@Data
public class Response {
private String code;
private String msg;
private Object data;
}With Graceful Response, use @ExceptionMapper to map exceptions to error codes:
@ExceptionMapper(code = "1404", msg = "找不到对象")
public class NotFoundException extends RuntimeException {}Service method can simply throw the exception; the component will produce a unified error response:
{
"status": {"code":"1404","msg":"找不到对象"},
"payload": {}
}2.2.5 Parameter validation
Graceful Response integrates with JSR‑303/Hibernate Validator. By adding @ValidationStatusCode you can set a custom error code for validation failures:
@Data
public class UserInfoQuery {
@NotNull(message = "userName is null !")
@Length(min = 6, max = 12)
@ValidationStatusCode(code = "520")
private String userName;
}When validation fails, the response contains the specified code (e.g., 520) and the validation message:
{
"status": {"code":"520","msg":"userName is null !"},
"payload": {}
}Controller method parameters can also be annotated with @ValidationStatusCode to unify error codes:
public class Controller {
@RequestMapping("/validateMethodParam")
@ResponseBody
@ValidationStatusCode(code = "1314")
public void validateMethodParam(@NotNull(message = "userId不能为空") Long userId,
@NotNull(message = "userName不能为空") Long userName) {
// business logic
}
}If validation fails, the response is:
{
"status": {"code":"1314","msg":"userId不能为空"},
"payload": {}
}2.2.6 Custom response format
Two built‑in response styles can be selected via graceful-response.response-style (0 or 1). Example for style 0:
{
"status": {"code":1007,"msg":"有内鬼,终止交易"},
"payload": {}
}Example for style 1:
{
"code":"1404",
"msg":"not found",
"data": {}
}If neither style fits, you can implement a custom response format.
Third‑party integrations (Swagger, executor, etc.)
Custom response
Exception pass‑through
Exception alias
Common configuration items
The project has over 200 stars on GitHub; see https://github.com/feiniaojin/graceful-response for more details.
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.
Java High-Performance Architecture
Sharing Java development articles and resources, including SSM architecture and the Spring ecosystem (Spring Boot, Spring Cloud, MyBatis, Dubbo, Docker), Zookeeper, Redis, architecture design, microservices, message queues, Git, etc.
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.
