自定义校验,多个参数唯一性 springboot+mybatis | 您所在的位置:网站首页 › mybatisplus去重 › 自定义校验,多个参数唯一性 springboot+mybatis |
import com.orisdom.dto.ApiResult;import com.orisdom.utils.BusinessException;import lombok.extern.slf4j.Slf4j;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.dao.DuplicateKeyException;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.servlet.NoHandlerFoundException; import javax.validation.ConstraintViolationException;import javax.validation.ValidationException; /** * 统一异常处理 */@Slf4j@ControllerAdvicepublic class GlobalExceptionHandler { private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class); @ExceptionHandler(value = BusinessException.class) @ResponseBody public ApiResult handleBusinessException(BusinessException be) { if (be.getStatus() == -1) { return ApiResult.expired(be.getMessage()); } return ApiResult.fail(be.getMessage()); } @ExceptionHandler(value = RuntimeException.class) @ResponseBody public ApiResult handleRuntimeException(RuntimeException e) { LOG.error("系统异常", e); return ApiResult.fail("系统异常,操作失败"); } // 参数校验异常处理 =========================================================================== // MethodArgumentNotValidException是springBoot中进行绑定参数校验时的异常,需要在springBoot中处理,其他需要处理ConstraintViolationException异常进行处理. /** * 方法参数校验 */ @ExceptionHandler(MethodArgumentNotValidException.class) @ResponseBody public ApiResult handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { log.error("方法参数校验:{}", e.getMessage()); return ApiResult.fail(e.getBindingResult().getFieldError().getDefaultMessage()); } /** * ValidationException */ @ExceptionHandler(ValidationException.class) @ResponseBody public ApiResult handleValidationException(ValidationException e) { log.error("ValidationException:", e); return ApiResult.fail(e.getCause().getMessage()); } /** * ConstraintViolationException */ @ExceptionHandler(ConstraintViolationException.class) @ResponseBody public ApiResult handleConstraintViolationException(ConstraintViolationException e) { log.error("ValidationException:" + e.getMessage(), e); return ApiResult.fail(e.getMessage()); } @ExceptionHandler(NoHandlerFoundException.class) @ResponseBody public ApiResult handlerNoFoundException(Exception e) { return ApiResult.fail("路径不存在,请检查路径是否正确"); } @ExceptionHandler(DuplicateKeyException.class) @ResponseBody public ApiResult handleDuplicateKeyException(DuplicateKeyException e) { return ApiResult.fail("数据重复,请检查后提交"); } } |
CopyRight 2018-2019 实验室设备网 版权所有 |