Spring的基础

统一异常处理

如果在业务逻辑中出现异常,通常是在最外层的Controller中进行try catch捕获处理,但是这样每一个controller都需要进行try catch,而Spring提供了全局统一异常处理的方式处理拦截Controller中暴露的异常错误。

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

@ExceptionHandler(Exception.class)
public ResultWrapper globalException() {
return new ResultWrapper("全局错误码","全局异常");
}

@ExceptionHandler(NullPointerException.class)
public ResultWrapper customException(HttpServletResponse response,NullPointerException ex){
//从异常中获取
return new ResultWrapper("错误码","错误信息");
}
}

参数校验

1
2
3
4
5
6
7
@Data
@Builder
public class ResultWrapper<T>{
private String code;
private String message;
private T data;
}
1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
1
2
3
4
5
6
7
8
9
10
11
12
@Data
public class LoginDTO {
@NotNull(message = "用户名不能为空")
private String userName;

@NotBlank(message = "密码不能为空")
@Length(min = 6, message = "密码长度至少6位")
private String password;

@Email
private String email;
}
1
2
3
4
5
6
7
8
@RestController
public class LoginController {
@PostMapping("/login")
public ResultWrapper login(@RequestBody @Valid LoginDTO loginDTO) {
//登录逻辑
return ResultWrapper();
}
}

但是这样会直接将返回的message返回到前端,而不是我们定义的BaseResult返回格式,需要再进行一层结果集包装。

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


@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultWrapper methodArgumentNotValidException(MethodArgumentNotValidException e) {
List<ObjectError> errors = e.getBindingResult().getAllErrors();
// 已经设置了快速失败,可以默认取首个错误即可
StringBuffer sb = new StringBuffer();
List<String> errorArr = Lists.newArrayList();
for (ObjectError error : errors) {
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
errorArr.add(fieldError.getField() + fieldError.getDefaultMessage());
} else {
errorArr.add(error.getObjectName() + error.getDefaultMessage());
}
}
String errMsg = String.join(";", errorArr.toArray(new String[]{}));
return new ResultWrapper("错误码xxx", errMsg);
}
}

全局异常处理类

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
@ControllerAdvice
public class GlobalExceptionAdvice {

//自定义异常
@ResponseBody
@ExceptionHandler({BusinessException.class})
public ResultWrapper bizException(BusinessException e) {
log.error("出现异常:{}", e);
return ResultWrapper.builder().code(e.getErrorCode()).msg(e.getMessage()).build();
}

//参数异常
@ResponseBody
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResultWrapper methodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("出现异常:{}", e);
List<ObjectError> errors = e.getBindingResult().getAllErrors();
// 已经设置了快速失败,可以默认取首个错误即可
StringBuffer sb = new StringBuffer();
List<String> errorArr = Lists.newArrayList();
for (ObjectError error : errors) {
if (error instanceof FieldError) {
FieldError fieldError = (FieldError) error;
errorArr.add(fieldError.getField() + fieldError.getDefaultMessage());
} else {
errorArr.add(error.getObjectName() + error.getDefaultMessage());
}
}
String errMsg = String.join(";", errorArr.toArray(new String[]{}));
return ResultWrapper.builder().code(StateCodeEnum.METHOD_ARGUMENT_NOT_VALID.getCode()).msg(errMsg).build();
}

@ResponseBody
@ExceptionHandler(ConstraintViolationException.class)
public ResultWrapper constraintViolationException(ConstraintViolationException e) {
// 拦截单个参数校验异常捕获
log.error("出现异常:{}", e);
// @RequestParam 参数校验失败
StringBuffer sb = new StringBuffer();
List<String> errorArr = Lists.newArrayList();
for (ConstraintViolation constraint : e.getConstraintViolations()) {
errorArr.add(constraint.getInvalidValue() + "非法" + constraint.getMessage());
}
String errMsg = String.join(";", errorArr.toArray(new String[]{}));
return ResultWrapper.builder().code(StateCodeEnum.CONSTRAINT_VIOLATION.getCode()).msg(errMsg).build();
}

//全局异常
@ResponseBody
@ExceptionHandler(Exception.class)
public ResultWrapper exception(Exception e) {
log.error("出现异常:{}", e);
return ResultWrapper.builder().code(StateCodeEnum.ERROR.getCode()).msg(e.getMessage()).build();
}


/**
* 参数错误类型转换异常
*
* @param e
* @return
*/
@ResponseBody
@ExceptionHandler(HttpMessageConversionException.class)
public ResultWrapper parameterTypeConvertException(HttpMessageConversionException e) {
return ResultWrapper.builder().code(StateCodeEnum.ERROR.getCode()).msg(e.getMessage()).build();
}
}

最后更新: 2021年05月06日 21:15

原始链接: https://midkuro.gitee.io/2020/10/21/spring-base/

× 请我吃糖~
打赏二维码