《Spring Boot错误处理从入门到实战:小白也能搞定的异常处理手册》

🌟 前言

“为什么我的Spring Boot接口一报错就显示Whitelabel Error Page?”
“如何让API返回统一的错误格式?”
本文将手把手带你解锁Spring Boot异常处理的六大核心姿势,从基础配置→全局处理→自定义异常→日志追踪,配套可运行的代码案例,新手也能轻松进阶!


一、Spring Boot默认错误处理机制

1.1 错误页面自动配置

当应用抛出异常时,Spring Boot会自动跳转到/error路径:

// 模拟异常  
@GetMapping("/demo")  
public String demo() {  
    throw new RuntimeException("测试异常!");  
}  

📌现象:访问/demo会显示默认的Whitelabel错误页(含状态码、错误信息)

1.2 默认错误响应结构(JSON格式)

若请求头携带Accept: application/json,则返回JSON:

{  
  "timestamp": "2024-03-20T10:00:00",  
  "status": 500,  
  "error": "Internal Server Error",  
  "path": "/demo"  
}  

二、自定义错误页面(HTML版)

2.1 基础配置

resources/staticresources/templates下创建错误页面:

resources  
└── static  
    └── error  
        ├── 404.html    // 404专用页  
        └── 5xx.html    // 5xx通用页  

📌效果

  • 触发404时自动渲染404.html
  • 其他5xx错误显示5xx.html

2.2 高级定制:使用Thymeleaf动态渲染

<!-- templates/error/5xx.html -->  
<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">  
<head>  
    <title>错误提示</title>  
</head>  
<body>  
    <h1 th:text="${status} + ' 服务器开小差了~'"></h1>  
    <p>路径:<span th:text="${path}"></span></p>  
    <p>时间:<span th:text="${timestamp}"></span></p>  
</body>  
</html>  

三、全局异常处理(API统一响应)

3.1 创建统一响应体

@Data  
@AllArgsConstructor  
public class Result<T> {  
    private Integer code;  
    private String message;  
    private T data;  

    // 成功响应  
    public static <T> Result<T> success(T data) {  
        return new Result<>(200, "成功", data);  
    }  

    // 错误响应  
    public static <T> Result<T> error(Integer code, String message) {  
        return new Result<>(code, message, null);  
    }  
}  

3.2 全局异常处理器

使用@RestControllerAdvice捕获所有异常:

@RestControllerAdvice  
public class GlobalExceptionHandler {  

    // 处理所有未捕获异常  
    @ExceptionHandler(Exception.class)  
    public Result<Void> handleException(Exception e) {  
        return Result.error(500, "系统异常:" + e.getMessage());  
    }  

    // 处理自定义业务异常  
    @ExceptionHandler(BizException.class)  
    public Result<Void> handleBizException(BizException e) {  
        return Result.error(e.getCode(), e.getMessage());  
    }  

    // 处理参数校验异常  
    @ExceptionHandler(MethodArgumentNotValidException.class)  
    public Result<Void> handleValidException(MethodArgumentNotValidException e) {  
        String message = e.getBindingResult().getFieldError().getDefaultMessage();  
        return Result.error(400, "参数错误:" + message);  
    }  
}  

四、自定义业务异常体系

4.1 定义异常类

public class BizException extends RuntimeException {  
    private Integer code;  

    public BizException(Integer code, String message) {  
        super(message);  
        this.code = code;  
    }  

    // getter...  
}  

4.2 使用案例

@GetMapping("/user/{id}")  
public Result<User> getUser(@PathVariable Long id) {  
    User user = userService.findById(id);  
    if (user == null) {  
        throw new BizException(404, "用户不存在");  
    }  
    return Result.success(user);  
}  

五、HTTP状态码深度控制

5.1 自定义状态码响应

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "资源不存在")  
public class ResourceNotFoundException extends RuntimeException {  
    //...  
}  

5.2 覆盖默认状态码

application.properties中配置:

# 关闭Whitelabel错误页  
server.error.whitelabel.enabled=false  
# 自定义错误路径  
server.error.path=/my-error  

六、进阶技巧:异常日志追踪

6.1 集成Logback日志

<!-- pom.xml -->  
<dependency>  
    <groupId>ch.qos.logback</groupId>  
    <artifactId>logback-classic</artifactId>  
</dependency>  

6.2 异常日志记录

@Slf4j  
@RestControllerAdvice  
public class GlobalExceptionHandler {  

    @ExceptionHandler(Exception.class)  
    public Result<Void> handleException(Exception e, HttpServletRequest request) {  
        log.error("请求路径: {}", request.getRequestURI());  
        log.error("异常堆栈: ", e);  // 打印完整堆栈  
        return Result.error(500, "系统繁忙");  
    }  
}  

📚 实战总结(思维导图)

Spring Boot异常处理体系  
├─ 默认机制  
│  ├─ Whitelabel Error Page  
│  └─ /error 端点  
├─ 全局处理  
│  ├─ @RestControllerAdvice  
│  ├─ @ExceptionHandler  
│  └─ 统一响应体  
├─ 自定义异常  
│  ├─ 业务异常体系  
│  └─ 状态码注解  
└─ 辅助工具  
   ├─ 日志追踪  
   └─ 参数校验  

#SpringBoot实战 #错误处理 #API开发 #小白教程 #优快云博文

你在Spring Boot中遇到过哪些头疼的异常问题?
评论区分享你的经历,点赞最高的送《Spring Boot实战派》电子书!🚀


相关推荐

(转载需授权,侵权必究)

好的,关于这个问题我们今天就先分享到这里,希望能帮助到屏幕前为代码发愁的您。如果觉得有帮助,希望能在Taobao搜索“鹿溪IT工作室”买一个小项目来练手,友友们给个好评,支持一下创作者不易

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值