Graceful Response: Unified Response Wrapper and Exception Handling for Spring Boot Applications
Graceful Response is a Spring Boot library that provides unified response wrapping, global exception handling, custom error codes, validation support, and configurable response styles, enabling developers to write cleaner controller code, reduce boilerplate, and improve API consistency.
Graceful Response is a component built on the Spring Boot stack that offers a one‑stop solution for unified response encapsulation, global exception handling, and custom error‑code mapping, helping developers save time and improve code readability.
The project provides example code on GitHub (https://github.com/feiniaojin/graceful-response-example.git) with separate branches for Spring Boot 2.x and 3.x, matching the appropriate Graceful Response versions (3.2.1‑boot2 and 3.2.1‑boot3).
Quick start shows the typical verbose controller code used in many projects, highlighting problems such as low efficiency, repetitive boilerplate, and poor readability. By introducing Graceful Response, developers can return raw data objects directly and let the library automatically wrap them into a standard JSON structure.
To add the library, include the Maven dependency:
<dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>{latest.version}</version>
</dependency>Enable the component in the Spring Boot entry class with the @EnableGracefulResponse annotation:
@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}After enabling, a controller method can simply return a domain object:
@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 library will automatically produce a unified response such as:
{
"status": {"code": "0", "msg": "ok"},
"payload": {"id": 1, "name": "name1"}
}For command‑type endpoints that return void , Graceful Response still wraps a success payload:
{
"status": {"code": "200", "msg": "success"},
"payload": {}
}Instead of letting service methods return a custom Response object, developers can throw business exceptions annotated with @ExceptionMapper to bind an error code and message:
@ExceptionMapper(code = "1404", msg = "找不到对象")
public class NotFoundException extends RuntimeException {}Service interfaces remain clean:
public interface QueryService {
UserInfoView queryOne(Query query);
}Implementation can throw the custom exception directly:
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();
}
// ...business logic
}
}When the exception is thrown, Graceful Response captures it and returns a standardized JSON with the configured code and message.
Validation support is enhanced by the @ValidationStatusCode annotation, which assigns a specific error code to JSR‑303 validation failures. Example:
@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 contain code 520 and the corresponding message.
Method‑level validation can also specify a status code:
@RequestMapping("/validateMethodParam")
@ResponseBody
@ValidationStatusCode(code = "1314")
public void validateMethodParam(@NotNull(message = "userId不能为空") Long userId,
@NotNull(message = "userName不能为空") Long userName) {
// business logic
}Graceful Response offers two built‑in response styles controlled by the property graceful-response.response-style (0 or 1). Developers can also define a completely custom response format if needed.
Additional advanced features include integration with Swagger, custom response bodies, exception whitelisting, aliasing, and a collection of common configuration items. The project has gained over two hundred stars on GitHub, indicating broad community adoption.
For more details and the source code, visit the GitHub repository: https://github.com/feiniaojin/graceful-response .
Code Ape Tech Column
Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn
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.