Commit 2ed73d33 by 刘鑫

pref: 添加全局异常处理以及 参数校验

1 parent 33a7dc33
...@@ -110,6 +110,11 @@ ...@@ -110,6 +110,11 @@
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>io.sentry</groupId> <groupId>io.sentry</groupId>
<artifactId>sentry-spring-boot-starter</artifactId> <artifactId>sentry-spring-boot-starter</artifactId>
<version>6.22.0</version> <version>6.22.0</version>
......
...@@ -5,13 +5,18 @@ import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; ...@@ -5,13 +5,18 @@ import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.validation.Validator;
import java.time.LocalDate; import java.time.LocalDate;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
import java.util.Properties;
@Configuration @Configuration
public class OrderConfig { public class OrderConfig {
...@@ -39,4 +44,26 @@ public class OrderConfig { ...@@ -39,4 +44,26 @@ public class OrderConfig {
return builder; return builder;
} }
/**
* hibernate 验证器验证规则配置, 集成spring message
*
* @param messageSource spring message resource
* @return Validator
*/
@Bean
public Validator validator(MessageSource messageSource) {
LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
// 设置上方配置的国际化源
factoryBean.setValidationMessageSource(messageSource);
// 设置使用 HibernateValidator 校验器
factoryBean.setProviderClass(HibernateValidator.class);
Properties properties = new Properties();
// 设置 快速异常返回
properties.setProperty("hibernate.validator.fail_fast", "true");
factoryBean.setValidationProperties(properties);
// 加载配置
factoryBean.afterPropertiesSet();
return factoryBean.getValidator();
}
} }
/*
* Begin license text.
* Copyright (c) 2020 — 2021 Liu Xin lsy_xin@163.com
* All rights reserved
* End license text.
*/
package com.dituhui.pea.order.interceptor;
import com.dituhui.pea.common.BusinessException;
import com.dituhui.pea.common.Result;
import com.dituhui.pea.enums.StatusCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 全局异常处理基础类
*
* @author liuxin
*/
@ControllerAdvice
public class RBaseExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(RBaseExceptionHandler.class);
/**
* validator 参数校验错误 处理 form data方式调用接口校验失败抛出的异常
*
* @param bindException {@link BindException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = BindException.class)
public Result<?> handler(BindException bindException) {
String message = StringUtils.collectionToCommaDelimitedString(
bindException.getAllErrors()
.stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList())
);
LOGGER.error("【RBaseExceptionHandler】【BindException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message);
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message, null);
}
/**
* Hibernate Validator参数校验异常处理 处理 json 请求体调用接口校验失败抛出的异常
*
* @param e {@link MethodArgumentNotValidException}
* @return 参数校验失败信息
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<?> handler(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
String exceptionMsg = StringUtils.collectionToCommaDelimitedString(
bindingResult.getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.collect(Collectors.toList())
);
LOGGER.error("【RBaseExceptionHandler】【MethodArgumentNotValidException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), exceptionMsg);
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), exceptionMsg, null);
}
/**
* Spring Validator参数校验异常处理 处理单个参数校验失败抛出的异常
*
* @param ex {@link ConstraintViolationException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = ConstraintViolationException.class)
public Result<?> handler(ConstraintViolationException ex) {
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
String message = StringUtils.collectionToCommaDelimitedString(constraintViolations.stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.toList()));
LOGGER.error("【RBaseExceptionHandler】【ConstraintViolationException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage());
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), message, null);
}
/**
* Spring Validator参数校验异常处理
*
* @param ex {@link IllegalArgumentException}
* @return 参数校验失败信息
*/
@ExceptionHandler(value = IllegalArgumentException.class)
public Result<?> handler(IllegalArgumentException ex) {
LOGGER.error("【RBaseExceptionHandler】【IllegalArgumentException】---------->错误码:{},信息:{}",
StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage());
return new Result<>(StatusCodeEnum.COMMON_PARAM_EMPTY.getCode(), ex.getMessage(), null);
}
/**
* 业务异常处理
*
* @param ex BusinessException
* @return 错误提示信息
*/
@ExceptionHandler(value = BusinessException.class)
public Result<?> handler(BusinessException ex) {
LOGGER.error("[RBaseExceptionHandler]:【BusinessException】---->{}", ex.getMessage());
return Result.failed(ex.getMessage());
}
/**
* 未知错误类型处理
*
* @param ex exception
* @return 未知错误提示信息
*/
@ExceptionHandler(value = Exception.class)
public Result<?> handler(Exception ex) {
LOGGER.error("[RBaseExceptionHandler]:【Exception】---->{}\nstackTrace:{}",
ex.getMessage(), ex.getStackTrace());
return Result.failed();
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!