How Graceful Response Simplifies Spring Boot API Development
This article introduces Graceful Response, a Spring Boot library that provides unified response wrapping, global exception handling, and validation support, showing how it reduces boilerplate code, improves readability, and standardizes error codes across controllers and services.
Introduction
Graceful Response is a Spring Boot‑based response processor that offers one‑stop unified return‑value encapsulation, global exception handling, and custom error‑code support. Using Graceful Response in web‑API development can save a lot of time, improve code quality, and make logic clearer.
Problems with Typical Spring Boot Controllers
When developing Spring Boot APIs, developers often face low efficiency, repetitive code, and poor readability. A typical controller method manually creates a response object, validates parameters, calls the service layer, and handles exceptions, resulting in a lot of boilerplate.
@Controller
public class ExampleController {
@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(paramMap);
// 3. set result
res.setData(data);
res.setCode(0);
res.setMsg("ok");
return res;
} catch (Exception e) {
// 4. ugly try…catch
res.setCode(1);
res.setMsg("error");
return res;
}
}
}The above code suffers from three issues:
Low efficiency : most of the method is just wrapping the result.
Repetitive work : every endpoint repeats the same validation and error handling.
Poor readability : core business logic is hidden among boilerplate.
Quick Start with Graceful Response
Graceful Response is published to Maven Central. Add the dependency to your pom.xml:
<dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>{latest.version}</version>
</dependency>Enable the component in the Spring Boot entry class:
@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}Now a controller can simply return the business object without manual wrapping:
@Controller
public class UserController {
@RequestMapping("/get")
@ResponseBody
public UserInfoView get(Long id) {
log.info("id={}", id);
return UserInfoView.builder().id(id).name("name" + id).build();
}
}Graceful Response automatically produces a unified JSON response, e.g.:
{
"status": {"code": "0", "msg": "ok"},
"payload": {"id": 1, "name": "name1"}
}For command‑type endpoints that return void, Graceful Response still wraps the result:
@Controller
public class CommandController {
@RequestMapping("/command")
@ResponseBody
public void command() {
// business logic
}
} {
"status": {"code": "200", "msg": "success"},
"payload": {}
}Exception Mapping and Validation
Define custom exceptions with @ExceptionMapper to bind an error code and message:
@ExceptionMapper(code = "1404", msg = "Object not found")
public class NotFoundException extends RuntimeException {}When a service method throws NotFoundException, Graceful Response returns:
{
"status": {"code": "1404", "msg": "Object not found"},
"payload": {}
}For request‑parameter validation, use the standard JSR‑303 annotations together with @ValidationStatusCode to specify the error code returned on validation failure:
@Data
public class UserInfoQuery {
@NotNull(message = "userName is null !")
@Length(min = 6, max = 12)
@ValidationStatusCode(code = "520")
private String userName;
}If validation fails, the response will be:
{
"status": {"code": "520", "msg": "userName is null !"},
"payload": {}
}Method‑level validation works the same way:
@RequestMapping("/validateMethodParam")
@ResponseBody
@ValidationStatusCode(code = "1314")
public void validateMethodParam(@NotNull(message = "userId cannot be null") Long userId,
@NotNull(message = "userName cannot be null") Long userName) {
// business logic
} {
"status": {"code": "1314", "msg": "userId cannot be null"},
"payload": {}
}Response Style Configuration
Graceful Response provides two built‑in response formats. Configure the style with the property graceful-response.response-style:
Value 0 (default) returns {"status":{...},"payload":{...}}.
Value 1 returns {"code":"...","msg":"...","data":{...}}.
If neither format fits, you can implement a custom response body.
Advanced Features
Integration with third‑party components such as Swagger and job executors.
Custom response formats.
Exception pass‑through.
Exception aliasing.
Common configuration items.
The project has over 200 stars on GitHub and can be found at https://github.com/feiniaojin/graceful-response .
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.
Architect
Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.
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.
