MultipartFile文件上传限制
spring:
# 文件大小限制
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB
加入全局异常拦截器
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler {
@ExceptionHandler(MultipartException.class)
public R handleException(MultipartException e) {
log.error("Exception,exception:{}", e, e);
BaseResponseCode em = e.getBaseResponseCode();
return new R(em.getCode(), "文件过大,请上传小于100M文件!");
}
@ExceptionHandler(value = BusinessException.class)
R businessExceptionHandler(BusinessException e) {
log.error("Exception,exception:{}", e, e);
BaseResponseCode em = e.getBaseResponseCode();
return new R(em.getCode(), em.getMsg());
}
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public R handleValidException(MethodArgumentNotValidException e){
log.error("参数格式校验异常");
BindingResult bindingResult = e.getBindingResult();
HashMap<String, String> errorMap = Maps.newHashMap();
AtomicReference<String> errorMsg = new AtomicReference<>("");
bindingResult.getFieldErrors().forEach(fieldError -> {
errorMsg.set(fieldError.getDefaultMessage());
errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
});
return R.fail(errorMsg);
}
@ExceptionHandler
public R handle(ConstraintViolationException exception) {
log.error("methodArgumentNotValidExceptionHandler bindingResult.allErrors():{},exception:{}", exception, exception);
Set<ConstraintViolation<?>> violations = exception.getConstraintViolations();
StringBuilder builder = new StringBuilder();
for (ConstraintViolation<?> violation : violations) {
builder.append(violation.getMessage());
break;
}
return R.getResult(BaseResponseCode.METHOD_ARGUMENT_NOT_VALID_EXCEPTION.getCode(), builder.toString());
}
}