在使用springboot过程中,当使用全局异常处理,即通过@RestControllerAdvice注解来定义全局异常处理。在具体的处理方法中如果返回中文可能会出现中文乱码情况。
比如,下面代码是针对参数校验的异常处理:
@ExceptionHandler(ConstraintViolationException.class)
public BizResult notValidException(ConstraintViolationException ex) {
BizResult result = new BizResult();
result.setCode("500");
Set<ConstraintViolation<?>> constraintViolations = ex.getConstraintViolations();
if (!CollectionUtils.isEmpty(constraintViolations)) {
StringBuilder sb = new StringBuilder();
for (ConstraintViolation constraintViolation : constraintViolations) {
sb.append(constraintViolation.getMessage()).append(",");
}
String errorMessage = sb.toString();
if (errorMessage.length() > 1) {
errorMessage = errorMessage.substring(0, errorMessage.length() - 1);
}
result.setErrorMsg(errorMessage);
return result;
}
result.setErrorMsg(ex.getMessage());
return result;
}
此时,如果校验参数的注解中信息描述使用了中文,则返回结果为乱码。解决此问题的方法很简单。在application配置文件中配置如下设置:
spring.http.encoding.force=true
也就是说对请求参数和返回参数强制编码,默认使用UTF-8。
原文链接:《springboot全局异常处理中文乱码》
CSDN学院:《Spring Boot 视频教程全家桶》