How Graceful Response Simplifies Spring Boot API Development

Graceful Response is a Spring Boot component that provides unified response wrapping, global exception handling, and custom error codes, helping developers reduce boilerplate, improve code readability, and accelerate API development while maintaining consistent error responses.

Java Backend Technology
Java Backend Technology
Java Backend Technology
How Graceful Response Simplifies Spring Boot API Development

Introduction

Graceful Response is a component for Spring Boot that provides unified response wrapping, global exception handling, and custom error codes, helping developers save time and improve code quality.

Version Compatibility

Spring Boot version

Graceful Response version

Example branch

2.x

3.2.1-boot2

3.2.0-boot2

3.x

3.2.1-boot3

3.2.0-boot3

Quick Start

Current Spring Boot controller problems

Typical controller code contains repetitive validation, result wrapping and try‑catch logic, 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 {
            // validate params
            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;
        }
    }
}

Problems: low efficiency, duplicated code, low readability.

Adding Graceful Response

Include the dependency from Maven Central:

<dependency>
    <groupId>com.feiniaojin</groupId>
    <artifactId>graceful-response</artifactId>
    <version>{latest.version}</version>
</dependency>

Enable it with @EnableGracefulResponse on the main application class.

@EnableGracefulResponse
@SpringBootApplication
public class ExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(ExampleApplication.class, args);
    }
}

Controller methods can now return plain objects:

@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();
    }
}

Graceful Response automatically wraps the result into a unified JSON structure.

Exception handling

Define custom exceptions with @ExceptionMapper to bind error codes and messages.

@ExceptionMapper(code = "1404", msg = "Object not found")
public class NotFoundException extends RuntimeException {}

When the service throws this exception, the response becomes:

{
  "status": {"code":"1404","msg":"Object not found"},
  "payload": {}
}

Parameter validation

Combine Hibernate Validator with @ValidationStatusCode to return a unified error code for validation failures.

public class UserInfoQuery {
    @NotNull(message = "userName is null!")
    @Length(min = 6, max = 12)
    @ValidationStatusCode(code = "520")
    private String userName;
}

Invalid input yields:

{
  "status": {"code":"520","msg":"userName is null!"},
  "payload": {}
}

Custom response styles

Configure graceful-response.response-style=0 or =1 to switch between two built‑in response formats, or implement a custom format if needed.

The component also offers advanced features such as Swagger integration, custom response bodies, exception pass‑through, and common configuration options.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaException HandlingmavenSpring BootAPIResponse wrapper
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.