做实验要求把若依 GlobalExceptionHandler 里每个 handler 都真跑一次,说清楚哪个接口、怎么请求、抛的是什么异常。我一开始以为对着源码看看就行,真动手才发现有好几个压根不好构造,来回折腾了大半天。这篇把过程和结果记下来。

环境是 RuoYi-Vue 3.9.2 + Spring Boot 3 + JDK 17,MySQL 和 Redis 都在本地,请求用 Postman 发的,Apifox 一样。

一、这个类到底拦了什么

ruoyi-framework/src/main/java/com/ruoyi/framework/web/exception/GlobalExceptionHandler.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@RestControllerAdvice
public class GlobalExceptionHandler
{
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(AccessDeniedException.class) // 权限校验异常
@ExceptionHandler(HttpRequestMethodNotSupportedException.class) // 请求方式不支持
@ExceptionHandler(ServiceException.class) // 业务异常
@ExceptionHandler(MissingPathVariableException.class) // 缺少路径变量
@ExceptionHandler(MethodArgumentTypeMismatchException.class) // 参数类型不匹配
@ExceptionHandler(RuntimeException.class) // 未知运行时异常
@ExceptionHandler(Exception.class) // 系统异常
@ExceptionHandler(MethodArgumentNotValidException.class) // 参数校验失败
// 另外还有 BindException 和 DemoModeException,本文没涉及
}

@RestControllerAdvice 就是全局拦截,Controller 里抛出来的东西按类型进到对应方法,包成 AjaxResult 还给前端。

有个事得先说,不然测的时候会懵:这些接口返回的 HTTP 状态码全是 200。

因为 AjaxResult 本身就是个 HashMap,handler 方法上也没有 @ResponseStatus,Spring 就老老实实按 200 返回。真正的错误码在响应体的 code 里。所以别盯着 Postman 那个绿色 200 看,要翻 Body。

写个专门出错的 Controller

若依自带接口能覆盖一部分,但「缺少路径变量」「受检异常」这两类用自带接口不好构造。干脆自己写一个,一个方法对应一种异常。

ruoyi-admin/src/main/java/com/ruoyi/web/controller/tool/ExceptionTestController.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.ruoyi.web.controller.tool;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.exception.ServiceException;

/**
* 全局异常处理器测试接口
*/
@RestController
@RequestMapping("/test/exception")
public class ExceptionTestController
{
/**
* 权限校验异常:当前登录用户没有 test:exception:denied 这个权限
*/
@PreAuthorize("hasAuthority('test:exception:denied')")
@GetMapping("/denied")
public AjaxResult denied()
{
return AjaxResult.success("有权限才会走到这里");
}

/**
* 请求方式不支持:这个接口只允许 POST,用 GET 访问就会抛异常
*/
@PostMapping("/method")
public AjaxResult method()
{
return AjaxResult.success("请求方式正确");
}

/**
* 业务异常:库存不足时主动抛 ServiceException
*/
@GetMapping("/service")
public AjaxResult service(@RequestParam(defaultValue = "0") Integer stock)
{
if (stock <= 0)
{
throw new ServiceException("商品库存不足,下单失败");
}
return AjaxResult.success("下单成功");
}

/**
* 缺少路径变量:两个路径共用一个方法,走 /missing 时 id 变量根本不存在
*/
@GetMapping({ "/missing/{id}", "/missing" })
public AjaxResult missing(@PathVariable("id") Long id)
{
return AjaxResult.success("id = " + id);
}

/**
* 参数类型不匹配:id 声明成 Long,传字母进来就会失败
*/
@GetMapping("/type/{id}")
public AjaxResult type(@PathVariable("id") Long id)
{
return AjaxResult.success("id = " + id);
}

/**
* 未知的运行时异常
*/
@GetMapping("/runtime")
public AjaxResult runtime()
{
throw new RuntimeException("测试未知的运行时异常");
}

/**
* 系统异常(受检异常)
*/
@GetMapping("/checked")
public AjaxResult checked() throws Exception
{
throw new Exception("测试系统异常");
}

/**
* 参数校验不通过:userName、phone 都不能为空
*/
@PostMapping("/valid")
public AjaxResult valid(@Valid @RequestBody ValidForm form)
{
return AjaxResult.success(form);
}
}

class ValidForm
{
@NotBlank(message = "用户名不能为空")
private String userName;

@NotBlank(message = "手机号不能为空")
private String phone;

public String getUserName() { return userName; }
public void setUserName(String userName) { this.userName = userName; }
public String getPhone() { return phone; }
public void setPhone(String phone) { this.phone = phone; }
}

重新打包启动:

1
2
mvn clean package -DskipTests
java -jar ruoyi-admin/target/ruoyi-admin.jar

日志里打出若依那个 ASCII 横幅和 Started RuoYiApplication in 20.135 seconds 就算起来了。端口 8080,context-path 是 /,地址直接从根写。

八个异常挨个点

1. AccessDeniedException(权限校验异常)

权限这条最容易踩空。GET /test/exception/denied 带 token 请求,方法上标了 @PreAuthorize("hasAuthority('test:exception:denied')"),当前用户没这个权限。

1
2
3
4
{
"msg": "没有权限,请联系管理员授权",
"code": 403
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleAccessDeniedException,39] -
请求地址'/test/exception/denied',权限校验失败'Access Denied'

Postman 实测:权限校验异常返回 403

@PreAuthorize 是方法级注解,鉴权失败由 AOP 抛 AccessDeniedException,抛点在 Controller 方法执行过程中,还在 DispatcherServlet 里面,所以能被 @RestControllerAdvice 接住。

这里我卡了一会儿:别照着若依的写法用 @ss.hasPermi('xxx')。admin 的权限集合里存的是 *:*:*,PermissionService.hasPermissions() 里有一句 permissions.contains(Constants.ALL_PERMISSION),超管直接返回 true,你写个根本不存在的权限也照样能进,403 永远出不来。换成 Spring 原生的 hasAuthority(),admin 的 authority 就是 *:*:*,跟字符串对不上,必拒。

真想用若依原生写法测,得换个普通角色账号,只勾「用户查询」,然后去调 /system/user/remove。

2. HttpRequestMethodNotSupportedException(请求方式不支持)

GET /test/exception/method 就能出来,方法声明的是 @PostMapping,用 GET 打过去必然不认。

1
2
3
4
{
"msg": "Request method 'GET' is not supported",
"code": 500
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleHttpRequestMethodNotSupported,51] -
请求地址'/test/exception/method',不支持'GET'请求

Postman 实测:请求方式不支持

不用自己写接口也能测,而且连 token 都不用带:GET http://localhost:8080/login。SysLoginController 里写的是 @PostMapping("/login"),用 GET 访问返回的 JSON 一模一样。

Postman 实测:用自带的 /login 触发

RequestMappingHandlerMapping 按路径找到了 handler,但方法对不上,于是抛这个异常。方法体还没进去,不过还在 DispatcherServlet 范围内,所以走全局处理器。

3. ServiceException(业务异常)

GET /test/exception/service,stock 默认 0,直接进 stock <= 0 分支主动抛。

1
2
3
4
{
"msg": "商品库存不足,下单失败",
"code": 500
}

日志:

1
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleServiceException,61] - 商品库存不足,下单失败

Postman 实测:业务异常

自带接口里也有真的业务异常。PUT /system/user,Body 传超管自己的 userId:

1
{"userId": 1, "userName": "admin"}

返回「不允许操作超级管理员用户」。

Postman 实测:改超管触发 ServiceException

SysUserController.edit() 第一行就是 userService.checkUserAllowed(user),进去之后:

1
2
3
4
if (StringUtils.isNotNull(user.getUserId()) && user.isAdmin())
{
throw new ServiceException("不允许操作超级管理员用户");
}

方法第一行就抛,后面的更新逻辑压根不执行,所以拿 admin 测这条不会真把超管改坏。

有个容易搞混的:DELETE /system/user/1 删当前登录的自己,返回的是

1
{"msg":"当前用户不能删除","code":500}

看着像,但它不是异常处理器给的,是 Controller 里 return error("当前用户不能删除") 直接返回,只是 AjaxResult 结构一样。区分办法是看日志:走异常的有 ERROR c.r.f.w.e.GlobalExceptionHandler 那条,这个没有。

ServiceException 是若依自定义的 RuntimeException 子类,可以带业务码。处理器里那个三元判断就是干这个的:

1
2
Integer code = e.getCode();
return StringUtils.isNotNull(code) ? AjaxResult.error(code, e.getMessage()) : AjaxResult.error(e.getMessage());

new ServiceException("xx", 601) 会把 601 原样塞进 code,不带码的统一 500。

4. MissingPathVariableException(缺少必需的路径变量)

这个最难构造。正常情况路径变量对不上就是 404,压根走不到这儿。

接口是 GET /test/exception/missing,关键是这行:

1
2
@GetMapping({ "/missing/{id}", "/missing" })
public AjaxResult missing(@PathVariable("id") Long id)

请求 /test/exception/missing,返回:

1
2
3
4
{
"msg": "请求路径中缺少必需的路径变量[id]",
"code": 500
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleMissingPathVariableException,73] -
请求路径中缺少必需的路径变量'/test/exception/missing',发生系统异常.

Postman 实测:缺少路径变量

注意 handler 是找到了的,不是 404。/test/exception/missing/5 匹配 "/missing/{id}",/test/exception/missing 匹配 "/missing",两个都指向同一个方法。问题出在参数解析:PathVariableMethodArgumentResolver 去 UriTemplateVariables 里取 id,取出来是 null,而 @PathVariable 的 required 默认 true,于是抛。

一句话概括触发条件:路径匹配上了,但方法要的路径变量没有值。除了双路径共用一个方法,URI 模板写错也会,比如方法上写 @RequestMapping("/a/{id}"),参数却写 @PathVariable("uid")。

对比若依自带的 /system/user/{userId}:

1
2
@GetMapping(value = { "/", "/{userId}" })
public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)

一模一样的双路径,但人家把 required 设成了 false,访问 /system/user 正常返回。官方就是靠这个绕开的。

5. MethodArgumentTypeMismatchException(参数类型不匹配)

GET /test/exception/type/abc,id 声明成 Long,传了 abc。

1
2
3
4
{
"msg": "请求参数类型不匹配,参数[id]要求类型为:'java.lang.Long',但输入值为:'abc'",
"code": 500
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleMethodArgumentTypeMismatchException,89] -
请求参数类型不匹配'/test/exception/type/abc',发生系统异常.

Postman 实测:参数类型不匹配

自带接口也行,GET /system/user/abc:

1
{"msg":"请求参数类型不匹配,参数[userId]要求类型为:'java.lang.Long',但输入值为:'abc'","code":500}

Postman 实测:用自带的 /system/user/abc 触发

@RequestParam Integer pageNum 传 pageNum=abc 也是同一个异常,Query 参数和路径变量在 Spring 里走的是同一套转换逻辑。

顺带说下,处理器里对 value 做了 EscapeUtil.clean() 转义。因为异常信息会把用户输入原样拼回 JSON,不转义就是个 XSS 口子。这地方写挺细的。

6. RuntimeException(未知运行时异常)

这个得自己写,方法体里就一句 throw new RuntimeException("测试未知的运行时异常"),访问 GET /test/exception/runtime。

1
2
3
4
{
"msg": "测试未知的运行时异常",
"code": 500
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleRuntimeException,100] -
请求地址'/test/exception/runtime',发生未知异常.

Postman 实测:RuntimeException

AjaxResult.error(e.getMessage()) 把 message 直接吐给前端了。生产环境一般不建议,会暴露内部细节,不过若依默认就这样,调试方便。

这个 handler 和 ServiceException、AccessDeniedException 是兜底关系。Spring 挑处理器找的是最精确的类型,ServiceException extends RuntimeException,所以抛 ServiceException 时走 handleServiceException,轮不到这里。

7. Exception(系统异常)

受检异常没法在普通方法里直接 throw,签名上得写 throws,所以这个接口看着有点怪:

1
2
3
4
public AjaxResult checked() throws Exception
{
throw new Exception("测试系统异常");
}

GET /test/exception/checked:

1
2
3
4
{
"msg": "测试系统异常",
"code": 500
}

日志:

1
2
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleException,111] -
请求地址'/test/exception/checked',发生系统异常.

Postman 实测:受检异常 Exception

所有异常的最终兜底就是它。Spring 6.1 之后 404 抛的 NoResourceFoundException 也落在这儿:

1
2
GET /test/exception/nothing
→ {"msg":"No static resource test/exception/nothing for request '/test/exception/nothing'.","code":500}

所以路径写错拿到的是 500 不是 404,这个算若依的小毛病,前端看到只会以为是服务端挂了。

8. MethodArgumentNotValidException(方法参数无效)

POST /test/exception/valid,Content-Type: application/json,Body:

1
{"userName":"","phone":""}
1
2
3
4
{
"msg": "用户名不能为空",
"code": 500
}

日志这一条特别长:

1
2
3
4
5
ERROR c.r.f.w.e.GlobalExceptionHandler - [handleMethodArgumentNotValidException,132] -
Validation failed for argument [0] in public com.ruoyi.common.core.domain.AjaxResult
com.ruoyi.web.controller.tool.ExceptionTestController.valid(...ValidForm) with 2 errors:
[Field error in object 'validForm' on field 'userName': rejected value []; ... default message [用户名不能为空]]
[Field error in object 'validForm' on field 'phone': rejected value []; ... default message [手机号不能为空]]

Postman 实测:参数校验失败

自带接口:POST /system/user,Body {"userName":"","nickName":""},返回「用户账号不能为空」。来源是 SysUser 上的注解:

1
2
3
@Xss(message = "用户账号不能包含脚本字符")
@NotBlank(message = "用户账号不能为空")
private String userName;

能触发的前提是参数上有 @Valid 或 @Validated,且 Body 是 JSON。若依 Controller 里到处是这组合:

1
public AjaxResult add(@Validated @RequestBody SysUser user)

注意看日志:明明两个字段都错了,返回的却只有「用户名不能为空」。因为处理器取的是 getBindingResult().getFieldError().getDefaultMessage(),getFieldError() 拿单个,不是 getFieldErrors()。想看全部得自己改代码。

容易混的两个,区分一下:

  • MethodArgumentNotValidException:@RequestBody + @Valid,JSON 参数校验失败
  • BindException:表单/Query 参数绑定校验失败,比如 @Validated SysUser user 不带 @RequestBody

若依对这两个都写了处理器,返回结构一样,只是取 message 的方式不同(BindException 用的是 getAllErrors().get(0))。

汇总

异常类型 触发接口 请求方式 code msg
AccessDeniedException /test/exception/denied GET + token 403 没有权限,请联系管理员授权
HttpRequestMethodNotSupportedException /test/exception/method GET(接口是 POST) 500 Request method ‘GET’ is not supported
ServiceException /test/exception/service GET 500 商品库存不足,下单失败
MissingPathVariableException /test/exception/missing GET 500 请求路径中缺少必需的路径变量[id]
MethodArgumentTypeMismatchException /test/exception/type/abc GET 500 请求参数类型不匹配,参数[id]要求类型为:’java.lang.Long’,但输入值为:’abc’
RuntimeException /test/exception/runtime GET 500 测试未知的运行时异常
Exception /test/exception/checked GET 500 测试系统异常
MethodArgumentNotValidException /test/exception/valid POST + JSON 500 用户名不能为空

自带接口能对照的:

异常类型 自带接口
HttpRequestMethodNotSupportedException GET /login
MethodArgumentTypeMismatchException GET /system/user/abc
ServiceException PUT /system/user,body {"userId":1,"userName":"admin"}
MethodArgumentNotValidException POST /system/user,body {"userName":""}

广告
广告正在加载中...
暂不开放评论,如对本文有任何疑问或建议,请联系apple@mr-wu.top
All Tags