@ControllerAdvice
@RestController
@Slf4j
public class ControllerExceptionHandler {
@ExceptionHandler ( value = Exception . class )
public ResponseEntity < String > validatorExceptionHandler ( Exception e) {
if ( e instanceof InternalAuthenticationServiceException ) {
log. warn ( "登录认证失败:{}" , e. getMessage ( ) ) ;
return new ResponseEntity < > ( AesEncryptUtils . encryptAES ( e. getMessage ( ) ) ,
HttpStatus . UNAUTHORIZED) ;
} else if ( e instanceof MissingServletRequestParameterException ) {
log. warn ( "缺少必填参数:{}" , e. getMessage ( ) ) ;
return new ResponseEntity < > ( AesEncryptUtils . encryptAES ( "缺少必填参数:" + e. getMessage ( ) ) ,
HttpStatus . BAD_REQUEST) ;
} else {
log. error ( "服务异常:{}" , e. getMessage ( ) , e) ;
return new ResponseEntity < > ( AesEncryptUtils . encryptAES ( "服务异常:" + e. getMessage ( ) ) ,
HttpStatus . INTERNAL_SERVER_ERROR) ;
}
}
@ExceptionHandler ( MethodArgumentNotValidException . class )
public ResponseEntity < String > handleMethodArgumentNotValidExceptionHandler ( MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex. getBindingResult ( ) ;
List < String > list = new ArrayList < > ( ) ;
List < FieldError > fieldErrors = bindingResult. getFieldErrors ( ) ;
for ( FieldError fieldError : fieldErrors) {
list. add ( fieldError. getField ( ) + ":" + fieldError. getDefaultMessage ( ) ) ;
}
Collections . sort ( list) ;
log. error ( "***入参属性错误:{}***" , JSON. toJSONString ( list) ) ;
String errMsg = AesEncryptUtils . encryptAES ( JSON. toJSONString ( list) ) ;
return new ResponseEntity < > ( errMsg, HttpStatus . BAD_REQUEST) ;
}
}