CommonExceptionAdvice.java
1.85 KB
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
package com.erry.iclear.dateInterface.api;
import com.erry.iclear.dateInterface.enums.ErrorCodeEnum;
import com.erry.iclear.dateInterface.api.response.ResultRS;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.http.HttpStatus;
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 org.springframework.web.bind.annotation.ResponseStatus;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author Administrator
*/
@ControllerAdvice
@ResponseBody
@Slf4j
public class CommonExceptionAdvice {
@Autowired
private MessageSource messageSource;
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler({MethodArgumentNotValidException.class,NullPointerException.class})
public ResultRS handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("参数验证失败:{}", e.getMessage());
BindingResult result = e.getBindingResult();
List<FieldError> errorList = e.getBindingResult().getFieldErrors();
List<String> errorMessages = errorList.stream().map(x->{
String itemMessage= messageSource.getMessage(x.getDefaultMessage(), null, x.getDefaultMessage(), LocaleContextHolder.getLocale());
return String.format("%s", itemMessage);
}).collect(Collectors.toList());
return new ResultRS(Boolean.FALSE, ErrorCodeEnum.ERROR_30002.getCode(),errorMessages.toString());
}
}