How Graceful Response Simplifies Spring Boot API Development
Graceful Response is a Spring Boot library that provides unified response wrapping, global exception handling, and customizable error codes, reducing boilerplate code, improving readability, and streamlining validation for Java web APIs.
Introduction
Graceful Response is a component built on the Spring Boot stack that offers one‑stop unified response wrapping, global exception handling, and custom error‑code mapping, helping developers write cleaner controller code and improve overall code quality.
Current Problems in Spring Boot API Development
Typical controller code contains repetitive validation, manual exception handling, and response wrapping, leading to low efficiency, duplicated effort, and poor readability.
<code>@Controller
public class Controller {
@GetMapping("/query")
@ResponseBody
public Response query(Map<String, Object> paramMap) {
Response res = new Response();
try {
if (illegal(paramMap)) {
res.setCode(1);
res.setMsg("error");
return res;
}
Object data = service.query(params);
res.setData(data);
res.setCode(0);
res.setMsg("ok");
return res;
} catch (Exception e) {
res.setCode(1);
res.setMsg("error");
return res;
}
}
}
</code>The above code suffers from low efficiency, duplicated labor, and low readability.
Graceful Response Features
Unified response format
Automatic exception‑to‑error‑code mapping via
@ExceptionMapperEnhanced validation support with
@ValidationStatusCodeConfigurable response styles
Quick Start
Add Maven Dependency
<code><dependency>
<groupId>com.feiniaojin</groupId>
<artifactId>graceful-response</artifactId>
<version>{latest.version}</version>
</dependency>
</code>Enable the Component
<code>@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
</code>Controller Layer
After enabling Graceful Response, controller methods can return plain objects; the library automatically wraps them.
<code>@Controller
@RequestMapping("/get")
@ResponseBody
public UserInfoView get(Long id) {
log.info("id={}", id);
return UserInfoView.builder().id(id).name("name" + id).build();
}
</code>The actual JSON response becomes:
<code>{
"status": {"code": "0", "msg": "ok"},
"payload": {"id": 1, "name": "name1"}
}
</code>Service Layer
Service methods no longer need to return a custom
Responseobject. Business exceptions can be thrown directly and mapped with
@ExceptionMapper.
<code>@ExceptionMapper(code = "1404", msg = "Object not found")
public class NotFoundException extends RuntimeException {}
public interface QueryService {
UserInfoView queryOne(Query query);
}
public class QueryServiceImpl implements QueryService {
@Resource
private UserInfoMapper mapper;
public UserInfoView queryOne(Query query) {
UserInfo user = mapper.findOne(query.getId());
if (Objects.isNull(user)) {
throw new NotFoundException();
}
// further business logic
}
}
</code>When
NotFoundExceptionis thrown, the response is automatically wrapped:
<code>{
"status": {"code": "1404", "msg": "Object not found"},
"payload": {}
}
</code>Validation Support
Graceful Response enhances JSR‑303 validation. By annotating a DTO with
@ValidationStatusCode, validation failures return a custom error code.
<code>@Data
public class UserInfoQuery {
@NotNull(message = "userName is null!")
@Length(min = 6, max = 12)
@ValidationStatusCode(code = "520")
private String userName;
}
</code>If validation fails, the response looks like:
<code>{
"status": {"code": "520", "msg": "userName is null!"},
"payload": {}
}
</code>Response Style Configuration
The library provides two built‑in response styles configurable via
graceful-response.response-style(0 or 1). If neither fits, developers can define a custom format.
Project Links
GitHub repository: https://github.com/feiniaojin/graceful-response
Demo screenshots:
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.