参数校验

This commit is contained in:
2025-04-30 13:34:09 +08:00
parent 99e002f054
commit 4877206761
2 changed files with 43 additions and 23 deletions

View File

@ -29,6 +29,21 @@ import java.util.List;
public class GlobalExceptionHandler {
// 处理参数类型不匹配的异常GET请求
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public BaseResponse<?> handleMethodArgumentTypeMismatchException(MethodArgumentTypeMismatchException ex) {
return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数类型不匹配: " + ex.getName());
}
// 处理消息体解析失败的异常POST请求
@ExceptionHandler(HttpMessageNotReadableException.class)
public BaseResponse<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("HttpMessageNotReadableException", e);
return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求体不能为空或格式无效");
}
// 处理参数绑定失败的异常
@ExceptionHandler(MethodArgumentNotValidException.class)
public BaseResponse<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
@ -36,29 +51,15 @@ public class GlobalExceptionHandler {
// 按字段名排序,确保每次返回的顺序一致
e.getBindingResult().getFieldErrors().stream()
.sorted(Comparator.comparing(FieldError::getField)) // 按字段名排序
.forEach(fieldError -> errors.append("Field: ")
.forEach(fieldError -> errors.append("参数: ")
.append(fieldError.getField())
.append(" | Error: ")
.append(" | 错误: ")
.append(fieldError.getDefaultMessage())
.append("; "));
return ResultUtils.error(ErrorCode.PARAMS_ERROR, errors.toString());
}
// // 处理参数类型不匹配的异常
// @ExceptionHandler(MethodArgumentTypeMismatchException.class)
// public ResponseEntity<String> handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex) {
// return ResponseEntity.badRequest().body("Invalid value for parameter: " + ex.getName());
// }
// 处理消息体解析失败的异常
@ExceptionHandler(HttpMessageNotReadableException.class)
public BaseResponse<?> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
log.error("HttpMessageNotReadableException", e);
return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求体不能为空或格式无效");
}
// 处理业务异常
@ExceptionHandler(BusinessException.class)
@ -68,11 +69,11 @@ public class GlobalExceptionHandler {
}
// 处理运行时异常
@ExceptionHandler(RuntimeException.class)
public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
log.error("RuntimeException", e);
return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
}
// // 处理运行时异常
// @ExceptionHandler(RuntimeException.class)
// public BaseResponse<?> runtimeExceptionHandler(RuntimeException e) {
// log.error("RuntimeException", e);
// return ResultUtils.error(ErrorCode.SYSTEM_ERROR, "系统错误");
// }
}