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
package com.tanpu.feo.feojob.config;
import com.tanpu.common.api.CommonResp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
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.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
@Slf4j
public class ApiExceptionConfig {
/**
* 捕捉全局所有的异常
* @param e
* @return
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public CommonResp<String> errorHandler(Exception e) {
log.error("==========全局异常: {}", e.getMessage(), e);
return CommonResp.failed(e.getMessage());
}
/**
* 仅仅捕捉校验所产生的异常
* @param exception
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
@ResponseBody
public CommonResp<String> errorHandler(MethodArgumentNotValidException exception) {
StringBuilder errorInfo = new StringBuilder();
BindingResult bindingResult=null;
if(exception instanceof MethodArgumentNotValidException){
bindingResult= ((MethodArgumentNotValidException)exception).getBindingResult();
}
for(int i = 0; i < bindingResult.getFieldErrors().size(); i++){
if(i > 0){
errorInfo.append(",");
}
FieldError fieldError = bindingResult.getFieldErrors().get(i);
errorInfo.append(fieldError.getField()).append(" :").append(fieldError.getDefaultMessage());
}
log.error("==========数据校验异常: {}", errorInfo.toString());
return CommonResp.failed(errorInfo.toString());
}
}