How Graceful Response Simplifies Spring Boot API Error Handling
This article analyzes the inefficiencies and duplication in typical Spring Boot controller code, introduces the Graceful Response library, and provides step‑by‑step instructions—including Maven integration, annotation setup, controller and service examples, exception mapping, validation handling, and response style configuration—to achieve cleaner, unified API responses.
Graceful Response is a Spring Boot‑based component that offers a one‑stop solution for unified return value wrapping, global exception handling, and custom error codes, helping developers write cleaner controller code and improve overall code quality.
Why the existing approach is problematic
Typical Spring Boot controllers contain repetitive boilerplate: manual parameter validation, service invocation, result wrapping, and extensive try‑catch blocks. This leads to three main issues:
Low efficiency : Most of the method body is devoted to wrapping the result rather than business logic.
Duplicate work : Every endpoint repeats the same validation and wrapping code.
Poor readability : Core logic is hidden among redundant statements.
Example pseudo‑code illustrates these problems, showing a controller method that validates parameters, calls a service, manually sets a response object, and handles exceptions.
Quick start with Graceful Response
1. Add the Maven dependency
<dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>{latest.version}</version>
</dependency>The library publishes separate artifacts for Spring Boot 2.x (version 3.2.1-boot2) and 3.x (version 3.2.1-boot3); choose the one that matches your Spring Boot version.
2. Enable the component
Annotate the main application class with @EnableGracefulResponse:
@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}3. Simplify the controller
After enabling Graceful Response, a controller method can return the raw business object; the library automatically wraps it into a unified JSON structure.
@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();
}
}The actual HTTP response becomes:
{
"status": {"code": "0", "msg": "ok"},
"payload": {"id": 1, "name": "name1"}
}4. Handle command‑type endpoints
For void‑returning methods, Graceful Response still produces a wrapped response with a success code.
@Controller
public class Controller {
@RequestMapping("/command")
@ResponseBody
public void command() {
// business logic
}
}Response example:
{
"status": {"code": "200", "msg": "success"},
"payload": {}
}5. Clean up the service layer
Instead of returning a custom Response object from service methods, developers can throw business exceptions. By annotating exception classes with @ExceptionMapper, Graceful Response maps them to specific error codes and messages.
@ExceptionMapper(code = "1404", msg = "Object not found")
public class NotFoundException extends RuntimeException { }Service implementation can simply throw the exception:
public class QueryServiceImpl implements QueryService {
@Resource
private UserInfoMapper mapper;
public UserInfoView queryOne(Query query) {
UserInfo userInfo = mapper.findOne(query.getId());
if (Objects.isNull(userInfo)) {
throw new NotFoundException();
}
// further business logic
}
}The resulting JSON contains the mapped error code and message:
{
"status": {"code": "1404", "msg": "Object not found"},
"payload": {}
}6. Validation integration
Graceful Response enhances JSR‑303 validation. By adding @ValidationStatusCode to a constraint, the specified code is used when validation fails.
@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 is:
{
"status": {"code": "520", "msg": "userName is null!"},
"payload": {}
}Method‑parameter validation works similarly with @ValidationStatusCode on the controller method.
7. Configurable response styles
The library supports two built‑in response formats, selectable via the property graceful-response.response-style: 0 (default):
{
"status": {"code": 1007, "msg": "有内鬼,终止交易"},
"payload": {}
} 1:
{
"code": "1404",
"msg": "not found",
"data": {}
}Custom response bodies are also supported for special business needs.
8. Advanced features
Integration with third‑party components (Swagger, executors, etc.)
Custom response formats
Exception whitelisting
Exception aliasing
Common configuration items
The project’s source code and examples are available on GitHub: https://github.com/feiniaojin/graceful-response and the example repository https://github.com/feiniaojin/graceful-response-example.git.
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.
