This commit is contained in:
2026-08-13 16:53:39 +08:00
parent 5210ad34f3
commit ed48da0a78
27 changed files with 392 additions and 313 deletions
@@ -3,6 +3,8 @@ package com.yunhai.bschclassmanage.controller.Handler;
import com.yunhai.platform.utils.exception.ErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -30,4 +32,31 @@ public class ValidationExceptionHandler {
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
/**
* @RequestBody 反序列化失败(JSON 格式错 / 字段类型不符 / 未知字段被拒)。
* 不捕获会被平台兜底成 code:6 / 内部服务错误,这里把真实原因透出来。
*/
@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<Map<String, Object>> handleNotReadable(HttpMessageNotReadableException ex) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("code", ErrorCode.ERROR.getCode());
response.put("msg", "请求体(JSON)解析失败: " + (ex.getRootCause() != null ? ex.getRootCause().getMessage() : ex.getMessage()));
response.put("data", null);
response.put("timeNow", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
/**
* Content-Type 不是 application/json(如 text/plain、form 表单、缺省),@RequestBody 无法选择转换器。
*/
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public ResponseEntity<Map<String, Object>> handleMediaType(HttpMediaTypeNotSupportedException ex) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("code", ErrorCode.ERROR.getCode());
response.put("msg", "请求 Content-Type 不被支持: " + ex.getMessage());
response.put("data", null);
response.put("timeNow", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
}