package com.mindskip.xzs.configuration.spring.exception;
|
|
import com.mindskip.xzs.base.RestResponse;
|
import com.mindskip.xzs.base.SystemCode;
|
import com.mindskip.xzs.utility.ErrorUtil;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.validation.BindException;
|
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.stream.Collectors;
|
|
/**
|
* @version 2.2.0
|
* @description: 异常配置
|
* Copyright (C), 2020-2021, 武汉思维跳跃科技有限公司
|
* @date 2021 /9/7 9:45
|
*/
|
@ControllerAdvice
|
public class ExceptionHandle {
|
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
|
|
/**
|
* 异常拦截
|
*
|
* @param e the e
|
* @return the rest response
|
*/
|
@ExceptionHandler(Exception.class)
|
@ResponseBody
|
public RestResponse handler(Exception e) {
|
logger.error(e.getMessage(), e);
|
return new RestResponse<>(SystemCode.InnerError.getCode(), SystemCode.InnerError.getMessage());
|
}
|
|
/**
|
* 参数校验拦截
|
*
|
* @param e the e
|
* @return the rest response
|
*/
|
@ExceptionHandler(MethodArgumentNotValidException.class)
|
@ResponseBody
|
public RestResponse handler(MethodArgumentNotValidException e) {
|
String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
|
FieldError fieldError = (FieldError) file;
|
return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
|
}).collect(Collectors.joining());
|
return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
|
}
|
|
/**
|
* 参数绑定异常拦截
|
*
|
* @param e the e
|
* @return the rest response
|
*/
|
@ExceptionHandler(BindException.class)
|
@ResponseBody
|
public RestResponse handler(BindException e) {
|
String errorMsg = e.getBindingResult().getAllErrors().stream().map(file -> {
|
FieldError fieldError = (FieldError) file;
|
return ErrorUtil.parameterErrorFormat(fieldError.getField(), fieldError.getDefaultMessage());
|
}).collect(Collectors.joining());
|
return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
|
}
|
|
|
}
|