在spring boot开发中,你是否遇到过这样的困扰?
每个controller方法都要写一堆try-catch块,代码冗余到怀疑人生;前端抱怨接口返回格式不统一,有的返回json,有的返回html;系统报错时直接把数据库异常堆栈暴露给用户,安全隐患拉满……别慌!今天这篇文章带你彻底搞定全局异常处理,用一行代码替代所有重复的
try-catch,让异常处理变得优雅又高效!
一、为什么要学全局异常处理?看完你就懂了!
1.1 痛点驱动
想象一下:你有10个controller,每个都要处理nullpointerexception、illegalargumentexception,甚至还要处理业务自定义的“用户不存在”异常……代码重复率高达80%,改个返回格式就得改10个地方,这不是在写代码,是在“复制粘贴”!
1.2 核心价值
- 代码简洁:只需一个类集中处理所有异常,告别重复
try-catch。 - 响应统一:前端收到的永远是
{code: 200, msg: "成功", data: ...}格式,解析无压力。 - 安全可控:系统异常(如数据库崩溃)不暴露堆栈,业务异常(如“余额不足”)明确提示用户。
- 日志友好:异常信息集中记录,排查问题不用翻遍各个controller。
二、spring boot全局异常处理的核心实现
spring boot提供了超好用的@restcontrolleradvice注解(@controlleradvice+@responsebody的组合),专门用于前后端分离场景的全局异常处理。咱们直接上干货!
2.1 第一步:定义统一响应格式
前端需要“标准化”的错误提示,所以先定义一个通用的result类,所有接口返回值都用它包装。
@data
@allargsconstructor
@noargsconstructor
public class result<t> {
private integer code; // 状态码(200=成功,400=参数错误,500=系统错误)
private string msg; // 提示信息
private t data; // 业务数据(可选)
// 快速构建成功响应(带数据)
public static <t> result<t> success(t data) {
return new result<>(200, "操作成功", data);
}
// 快速构建失败响应(自定义code和msg)
public static <t> result<t> error(integer code, string msg) {
return new result<>(code, msg, null);
}
}2.2 第二步:编写全局异常处理器
用@restcontrolleradvice标记一个类,spring boot会自动扫描并拦截所有controller的异常。重点是用@exceptionhandler指定要处理的异常类型。
场景1:处理业务自定义异常(比如“用户不存在”)
业务中经常需要抛“用户不存在”、“订单已支付”这类异常,咱们可以自定义异常类,然后在全局处理器里捕获。
步骤1:定义业务异常类
// 自定义业务异常(继承runtimeexception,方便在service层抛出)
public class businessexception extends runtimeexception {
private integer code; // 业务错误码(如4001=用户不存在)
public businessexception(integer code, string msg) {
super(msg);
this.code = code;
}
public integer getcode() {
return code;
}
}步骤2:全局捕获业务异常
@restcontrolleradvice
public class globalexceptionhandler {
// 处理业务异常(比如用户不存在)
@exceptionhandler(businessexception.class)
public result<?> handlebusinessexception(businessexception e) {
return result.error(e.getcode(), e.getmessage());
}
}场景2:处理参数校验异常(@valid校验失败)
用@valid校验请求参数时,参数不合法会抛methodargumentnotvalidexception,咱们可以提取错误信息,友好提示用户。
// 全局处理参数校验异常(@requestbody参数校验失败)
@exceptionhandler(methodargumentnotvalidexception.class)
public result<?> handlevalidationexception(methodargumentnotvalidexception e) {
// 提取所有校验失败的字段信息(比如"用户名不能为空")
string errormsg = e.getbindingresult().getfielderrors().stream()
.map(fielderror::getdefaultmessage)
.collect(collectors.joining(";"));
return result.error(400, "参数校验失败:" + errormsg);
}场景3:处理系统未知异常(兜底方案)
数据库崩溃、空指针等系统级异常,必须捕获并返回通用提示,同时记录完整日志(避免暴露敏感信息)。
// 全局处理其他未捕获的异常(系统级错误)
@exceptionhandler(exception.class)
public result<?> handlesystemexception(exception e) {
// 记录完整异常堆栈(生产环境必加!)
log.error("系统发生未知异常,请求路径:{}", getrequestpath(), e);
// 返回友好提示(前端看到的是"服务器繁忙,请稍后再试")
return result.error(500, "服务器繁忙,请稍后再试");
}
// 辅助方法:获取当前请求路径(需要spring-web依赖)
private string getrequestpath() {
servletrequestattributes attributes = (servletrequestattributes) requestcontextholder.getrequestattributes();
return attributes == null ? "" : attributes.getrequest().getrequesturi();
}2.3 第三步:在业务中抛异常,测试效果!
现在,在service层抛出自定义异常,看看是否被全局处理器捕获。
@service
public class userservice {
public user getuserbyid(long id) {
// 模拟数据库查询(假设id=100的用户不存在)
user user = null;
if (user == null) {
throw new businessexception(4001, "用户id=" + id + "不存在"); // 抛业务异常
}
return user;
}
}
@restcontroller
@requestmapping("/users")
public class usercontroller {
@autowired
private userservice userservice;
@getmapping("/{id}")
public result<user> getuser(@pathvariable long id) {
user user = userservice.getuserbyid(id);
return result.success(user); // 正常返回
}
}测试结果:
- 当
id=100时,返回{"code":4001,"msg":"用户id=100不存在","data":null}(业务异常被捕获)。 - 当
id=1(存在用户)时,返回{"code":200,"msg":"操作成功","data":{...}}(正常响应)。
三、进阶玩法:这些场景也能轻松搞定!
3.1 自定义http状态码(比如404)
如果想让某些异常返回特定的http状态码(如“资源不存在”返回404),可以用@responsestatus注解。
// 自定义异常(标记为404状态码)
@responsestatus(httpstatus.not_found)
public class resourcenotfoundexception extends runtimeexception {
public resourcenotfoundexception(string msg) {
super(msg);
}
}
// 全局处理(可选,也可以直接用@responsestatus)
@exceptionhandler(resourcenotfoundexception.class)
public result<?> handleresourcenotfound(resourcenotfoundexception e) {
return result.error(404, e.getmessage());
}3.2 处理表单参数校验异常(@modelattribute)
如果是表单提交(非@requestbody),参数校验失败会抛bindexception,处理方式和methodargumentnotvalidexception类似:
@exceptionhandler(bindexception.class)
public result<?> handlebindexception(bindexception e) {
string errormsg = e.getbindingresult().getfielderrors().stream()
.map(fielderror::getdefaultmessage)
.collect(collectors.joining(";"));
return result.error(400, "参数校验失败:" + errormsg);
}3.3 记录异常日志的细节
全局处理中记录日志时,建议带上请求路径、用户id(如果有登录)等信息,方便排查问题:
@exceptionhandler(exception.class)
public result<?> handlesystemexception(exception e) {
// 获取请求路径
string path = getrequestpath();
// 获取用户id(假设从token中解析)
string userid = securityutils.getcurrentuserid();
// 记录日志(包含关键上下文信息)
log.error("系统异常 | 用户id={} | 路径={} | 异常信息={}",
userid, path, e.getmessage(), e);
return result.error(500, "服务器繁忙,请稍后再试");
}四、避坑指南:这些坑别踩!
4.1 全局异常不生效?
- 检查是否添加了
@restcontrolleradvice注解(别漏了@responsebody)。 - 检查异常类的包路径是否被spring扫描到(确保全局处理器和业务类在同一个或子包下)。
- 检查是否有局部
try-catch覆盖了全局处理(比如controller里自己catch了异常,没抛出去)。
4.2 生产环境暴露敏感信息?
- 系统异常(如
sqlexception)的msg不要直接返回给前端,用“服务器繁忙”代替。 - 日志中可以记录完整堆栈,但响应体里只保留友好提示。
4.3 自定义异常没被捕获?
- 确保自定义异常是
runtimeexception的子类(spring默认只捕获runtimeexception和error)。 - 如果是检查型异常(如
ioexception),需要在方法上声明throws,或手动抛runtimeexception包装。
五、总结:全局异常处理的学习路线
- 基础用法:用
@restcontrolleradvice+@exceptionhandler捕获所有异常,返回统一result。 - 业务异常:自定义
businessexception,在service层抛出,全局处理返回业务码。 - 参数校验:用
@valid+methodargumentnotvalidexception,提取校验错误信息。 - 系统异常:兜底处理
exception,记录日志并返回友好提示。 - 进阶优化:自定义状态码、记录请求上下文、处理表单参数异常。
掌握这些,你的spring boot项目异常处理将告别“屎山代码”,变得简洁、优雅、易维护!赶紧动手试试吧~ 有其他问题欢迎在评论区留言,我会一一解答! 😊
到此这篇关于spring boot全局异常处理保姆级教程从入门到实战(看完秒懂)的文章就介绍到这了,更多相关spring boot全局异常处理内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论