SpringBoot异常
# Spring 异常
在Spring中使用 @ControllerAdvice和@ExceptionHandler处理全局异常。
# 案例
全局异常处理
GlobalExceptionHandler
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
public Object illegalHandler(IllegalArgumentException e){
System.out.println("进入illegalHandler");
return ResponseEntity.status(400).body(R.failed(e.getMessage()));
}
@ExceptionHandler(Exception.class)
public Object common(Exception e){
System.out.println("进入commonHandler");
return ResponseEntity.status(400).body(e.getMessage());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
测试异常 HelloController
@RestController
@RequestMapping("/api")
public class HelloController {
@RequestMapping("/data")
public Object data(){
return R.ok("恭喜你,成功获取到数据");
}
@RequestMapping("/hello")
public Object hello(){
throw new IllegalArgumentException("无效参数");
}
@RequestMapping("/common")
public Object common(){
int i=5/0;
return "common";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
R
@Data
@NoArgsConstructor
@AllArgsConstructor
public class R {
private String code;
private String message;
private Object data;
public R(String code, String message) {
this.code = code;
this.message = message;
}
public static R ok(){
return ok(null);
}
public static R ok(Object data){
R r=new R("0","操作成功",data);
return r;
}
public static R failed(){
return failed(null);
}
public static R failed(Object data){
R r=new R("1","操作失败",data);
return r;
}
}
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
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
pom 文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Last Updated: 2024/07/26, 16:12:04