fix: handle ConstraintViolationException as 400 instead of 500

This commit is contained in:
2026-05-25 02:38:29 +08:00
parent 14b86df124
commit 769bf721f4
@@ -1,5 +1,7 @@
package cn.craftlabs.platform.api.config;
import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@@ -18,4 +20,20 @@ public class ApiExceptionHandler {
body.put("message", ex.getReason() != null ? ex.getReason() : "");
return ResponseEntity.status(ex.getStatusCode()).body(body);
}
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Map<String, Object>> handleConstraintViolation(ConstraintViolationException ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", HttpStatus.BAD_REQUEST.value());
body.put("message", "参数校验失败: " + ex.getMessage());
return ResponseEntity.badRequest().body(body);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleGeneral(Exception ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
body.put("message", "服务器内部错误");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(body);
}
}