Backend Development 16 min read

Standardized API Response, Global Exception Handling, and Logging Configuration in Spring Boot

This article presents a comprehensive guide on designing a unified JSON response structure, implementing global exception handling with @ControllerAdvice, and configuring Logback for console and file logging in Spring Boot applications, complete with code examples and best‑practice recommendations.

Top Architect
Top Architect
Top Architect
Standardized API Response, Global Exception Handling, and Logging Configuration in Spring Boot

The article explains the need for a unified API response format in front‑back communication, typically JSON.

Unified Result Structure

Defines a standard result with fields: success, code, message, data, and extra identifiers.

@Getter
public enum ResultCodeEnum {
    SUCCESS(true,20000,"成功"),
    UNKNOWN_ERROR(false,20001,"未知错误"),
    PARAM_ERROR(false,20002,"参数错误");
    private Boolean success;
    private Integer code;
    private String message;
    ResultCodeEnum(boolean success, Integer code, String message) {
        this.success = success;
        this.code = code;
        this.message = message;
    }
}

@Data
public class R {
    private Boolean success;
    private Integer code;
    private String message;
    private Map
data = new HashMap<>();
    private R() {}
    public static R ok() { /* ... */ }
    public static R error() { /* ... */ }
    public static R setResult(ResultCodeEnum result) { /* ... */ }
    public R data(Map
map) { this.setData(map); return this; }
    public R data(String key,Object value) { this.data.put(key, value); return this; }
    public R message(String message) { this.setMessage(message); return this; }
    public R code(Integer code) { this.setCode(code); return this; }
    public R success(Boolean success) { this.setSuccess(success); return this; }
}

Controller Usage

Shows how to return the unified result from a Spring MVC controller.

@RestController
@RequestMapping("/api/v1/users")
public class TeacherAdminController {
    @Autowired
    private UserService userService;
    @GetMapping
    public R list() {
        List
list = teacherService.list(null);
        return R.ok().data("itms", list).message("用户列表");
    }
}

Global Exception Handling

Describes using @ControllerAdvice and @ExceptionHandler to capture exceptions and return the unified result.

@ControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e) {
        e.printStackTrace();
        return R.error();
    }
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public R error(NullPointerException e) {
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.NULL_POINT);
    }
    @ExceptionHandler(CMSException.class)
    @ResponseBody
    public R error(CMSException e) {
        e.printStackTrace();
        return R.error().message(e.getMessage()).code(e.getCode());
    }
}

@Data
public class CMSException extends RuntimeException {
    private Integer code;
    public CMSException(Integer code, String message) { super(message); this.code = code; }
    public CMSException(ResultCodeEnum resultCodeEnum) { super(resultCodeEnum.getMessage()); this.code = resultCodeEnum.getCode(); }
    @Override
    public String toString() { return "CMSException{" + "code=" + code + ", message=" + getMessage() + '}'; }
}

Logging Configuration

Provides a Logback XML configuration for console and file logging across environments.

<configuration scan="true" scanPeriod="10 seconds">
    <property name="log.path" value="D:/Documents/logs/edu"/>
    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>debug</level>
        </filter>
        <encoder>
            <pattern>${CONSOLE_LOG_PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>
    <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${log.path}/edu_debug.log</file>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
            <charset>UTF-8</charset>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>${log.path}/web-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
                <maxFileSize>100MB</maxFileSize>
            </timeBasedFileNamingAndTriggeringPolicy>
            <maxHistory>15</maxHistory>
        </rollingPolicy>
        <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>debug</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>
    </appender>
<springProfile name="dev">
        <root level="info">
            <appender-ref ref="CONSOLE"/>
            <appender-ref ref="DEBUG_FILE"/>
            <appender-ref ref="INFO_FILE"/>
            <appender-ref ref="WARN_FILE"/>
            <appender-ref ref="ERROR_FILE"/>
        </root>
    </springProfile>
    <springProfile name="pro">
        <root level="info">
            <appender-ref ref="ERROR_FILE"/>
            <appender-ref ref="WARN_FILE"/>
        </root>
    </springProfile>
</configuration>

Additional notes cover logging exception details to files, using environment profiles (spring.profiles.active), and recommended tools such as the Grep Console plugin for colored console output.

BackendJavaException HandlingloggingSpring BootAPI designUnified Response
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login 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.