统一异常处理

在用spring Boot做web后台时,经常会出现异常,如果每个异常都自己去处理很麻烦,所以我们创建一个全局异常处理类来统一处理异常

代码:

Result.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
public class Result<T> {

/** 错误码. */
private Integer code;

/** 提示信息. */
private String msg;

/** 具体的内容. */
private T data;

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;
}

public T getData() {
return data;
}

public void setData(T data) {
this.data = data;
}
}

ResultUtil .java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class ResultUtil {

public static Result success(Object object) {
Result result = new Result();
result.setCode(0);
result.setMsg("成功");
result.setData(object);
return result;
}

public static Result success() {
return success(null);
}

public static Result error(Integer code, String msg) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
return result;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Entity
public class Gril {
@Id
@GeneratedValue
@NotNull(message = "这个id必传")
private Integer id;


public Integer getId(Integer id) {
return this.id;
}

public void setId(Integer id) {
this.id = id;
}
}

使用:

1
2
3
4
5
6
7
8
9
10
11
12
13
@RestController
public class GrilController {
//添加女生
@PostMapping(value = "/grils/{id}")
public Result<Gril> grilAdd(@Valid Gril gril, BindingResult bindingResult){

if(bindingResult.hasErrors()){
//这个是把gril里面的这个id必传返回给前端
return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
}
return ResultUtil.success(grilpepository.save(gril));
}
}

访问http://127.0.0.1:8081/grils

返回

1
2
3
4
5
{
"code": 1,
"msg": "这个id必传",
"data": null
}

访问http://127.0.0.1:8081/grils/2

返回

1
2
3
{
"id": 21
}

统一异常处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class GrilException extends RuntimeException{
private Integer code;

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

public Integer getCode() {
return code;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result Handle(Exception e){

if (e instanceof GrilException){
GrilException grilException = (GrilException) e;
return ResultUtil.error(grilException.getCode(),grilException.getMessage());

}else {
      //将系统异常以打印出来
logger.info("[系统异常]{}",e);
return ResultUtil.error(-1,"未知错误");
}

}
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Service
public class GirlService {
public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integer age = girl.getAge();
if (age < 10) {
//返回"你还在上小学吧" code=100
throw new GirlException(100,"你还在上小学吧");
}else if (age > 10 && age < 16) {
//返回"你可能在上初中" code=101
throw new GirlException(101,"你可能在上初中" );
}

}
}

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

@Autowired
private GirlService girlService;
@GetMapping(value = "girls/getAge/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception{
girlService.getAge(id);
}
}

image

异常是统一维护

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class GirlException extends RuntimeException{

private Integer code;

public GirlException(ResultEnum resultEnum) {
super(resultEnum.getMsg());
this.code = resultEnum.getCode();
}

public Integer getCode() {
return code;
}

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@ControllerAdvice
public class ExceptionHandle {

private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e) {
if (e instanceof GirlException) {
GirlException girlException = (GirlException) e;
return ResultUtil.error(girlException.getCode(), girlException.getMessage());
}else {
logger.error("【系统异常】{}", e);
return ResultUtil.error(-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
public enum ResultEnum {
UNKONW_ERROR(-1, "未知错误"),
SUCCESS(0, "成功"),
PRIMARY_SCHOOL(100, "我猜你可能还在上小学"),
MIDDLE_SCHOOL(101, "你可能在上初中"),

;

private Integer code;

private String msg;

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

public Integer getCode() {
return code;
}

public String getMsg() {
return msg;
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Service
public class GirlService {

@Autowired
private GirlRepository girlRepository;

public void getAge(Integer id) throws Exception{
Girl girl = girlRepository.findOne(id);
Integer age = girl.getAge();
if (age < 10) {
//返回"你还在上小学吧" code=100
throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
}else if (age > 10 && age < 16) {
//返回"你可能在上初中" code=101
throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
}

//如果>16岁,加钱
//...
}
}
1
2
3
4
5
6
7
8
9
10
11
12
@RestController
public class GirlController {


@Autowired
private GirlService girlService;


@GetMapping(value = "girls/getAge/{id}")
public void getAge(@PathVariable("id") Integer id) throws Exception{
girlService.getAge(id);
}

后记:在使用枚举类的时候ResultUtil.error(ResultEnum.UNKONW_ERROR)报错,具体原因待总结

参考:
springboot统一异常处理及返回数据的处理

0%