SpringBoot使用@ControllerAdvice、@ExceptionHandler、@ResponseBody进行全局异常处理,另外也有@RestControllerAdvice注解。本文使用@RestControllerAdvice。

一、全局异常处理

@RestControllerAdvice返回为Json格式,为@RequestMapping、@PostMapping、@GetMapping提供了@ExceptionHandler的功能。

1
2
3
4
5
6
7
8
9
10
11
12
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(NullPointerException.class)
public Object exception(NullPointerException e) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("code", 400);
params.put("msg", e.getMessage());
return params;
}

}

@ExceptionHandler表示要处理的异常。
注意:
1、不能使用两个@ExceptionHandler去处理同一个异常,也就是传入的参数不能相同,否则项目启动会报错。
2、如果一个异常同时被一个小范围的异常类和一个大范围的异常类覆盖,会选择小范围的异常处理器。
Controller如下:

1
2
3
4
5
6
7
8
9
@RestController
public class TestController {

@GetMapping("null")
public Object nullPoint() {
throw new NullPointerException("空指针异常");
}

}

浏览器中输入:localhost:8080/null

1
2
3
4
{
"msg":"空指针异常",
"code":400
}

二、自定义异常处理

1、自定义异常类

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
public class MyException extends RuntimeException {

private static final long serialVersionUID = 5331965491208438176L;

private Integer code;

private String msg;

public MyException(Integer code, String msg) {
this.code = code;
this.msg = msg;
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}

}

2、异常处理

1
2
3
4
5
6
7
8
9
10
11
12
@RestControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(MyException.class)
public Object myException(MyException e) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("code", e.getCode());
params.put("msg", e.getMsg());
return params;
}

}

Controller:

1
2
3
4
5
6
7
8
9
@RestController
public class TestController {

@GetMapping("my")
public Object myException() {
throw new MyException(400, "自定义异常");
}

}

浏览器中输入:localhost:8080/my

1
2
3
4
{
"msg":"自定义异常",
"code":400
}