编写异常Advice

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
package com.jhj.gulimall.product.exception;

import com.jhj.common.exception.BizCodeEnume;
import com.jhj.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
* @Description GulimallExceptionControllerAdvice
* @Author jhj
* @Date 2022/6/110:34
**/
@Slf4j
//处理哪个包下的异常
@RestControllerAdvice(basePackages = "com.jhj.gulimall.product.controller")
public class GulimallExceptionControllerAdvice {


//校验异常
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleVaildExceptinon(MethodArgumentNotValidException e){

log.error("检验错误{}",e.getMessage());
HashMap<String, String> errorMap = new HashMap<>();
e.getBindingResult().getFieldErrors().forEach((res)->{

errorMap.put(res.getField(),res.getDefaultMessage());
});
return R.error(BizCodeEnume.VAILD_EXCEPTION.getCode(), BizCodeEnume.VAILD_EXCEPTION.getMsg()).put("data",errorMap);
}

//校验异常
@ExceptionHandler(value = Throwable.class)
public R handleVaildExceptinon(Throwable e){


return R.error(BizCodeEnume.UNKNOW_EXCEPTION.getCode(), BizCodeEnume.UNKNOW_EXCEPTION.getMsg());
}
}

配置异常返回枚举(非必要)

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
package com.jhj.common.exception;

public enum BizCodeEnume {

UNKNOW_EXCEPTION(10000,"系统未知异常"),
VAILD_EXCEPTION(10001,"参数格式校验失败");

private int code;
private String msg;

BizCodeEnume(int code, String msg) {

this.code = code;
this.msg = msg;
}

public int getCode() {

return code;
}

public String getMsg() {

return msg;
}
}

除一些特定异常外 也可以自定义异常

1
2
3
4
5
6
7
8
9
package com.jhj.gulimall.product.exception;

public class MyException extends RuntimeException{

public MyException(String message) {

super("我的自定义异常");
}
}

作者声明

1
如有问题,欢迎指正!