Garage API : gestion d'erreurs robuste (JSON garanti)
Deploy to Pacha Family / deploy (push) Failing after 3s

- set_exception_handler global : toute exception PDO retourne du JSON
  au lieu d'une page HTML qui casse le JSON.parse côté client
- gOk() : JSON_INVALID_UTF8_SUBSTITUTE pour données UTF-8 corrompues,
  vérification du retour de json_encode
- db.php die() : retourne JSON au lieu de texte brut

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
perco
2026-05-11 17:31:29 +02:00
co-authored by Claude Sonnet 4.6
parent 7cacf4bdf5
commit 5ac4e51efb
2 changed files with 14 additions and 2 deletions
+2 -1
View File
@@ -35,6 +35,7 @@ try {
); );
$pdo->exec("SET collation_connection = utf8mb4_general_ci"); $pdo->exec("SET collation_connection = utf8mb4_general_ci");
} catch (\PDOException $e) { } catch (\PDOException $e) {
die("Erreur connexion BDD famille : " . $e->getMessage()); if (!headers_sent()) { header('Content-Type: application/json'); http_response_code(500); }
die(json_encode(['ok' => false, 'error' => 'Erreur BDD : ' . $e->getMessage()]));
} }
?> ?>
+12 -1
View File
@@ -6,6 +6,12 @@ header('Content-Type: application/json');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; } if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }
set_exception_handler(function(\Throwable $e) {
if (!headers_sent()) { header('Content-Type: application/json'); http_response_code(500); }
echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
exit;
});
require_once dirname(__DIR__, 2) . '/includes/db.php'; require_once dirname(__DIR__, 2) . '/includes/db.php';
$UPLOAD_DIR = '/uploads/garage/'; $UPLOAD_DIR = '/uploads/garage/';
@@ -14,7 +20,12 @@ if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0755, true); }
$method = $_SERVER['REQUEST_METHOD']; $method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? ''; $action = $_GET['action'] ?? '';
function gOk($d) { echo json_encode(['ok' => true, 'data' => $d]); exit; } function gOk($d) {
$flags = JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE;
$json = json_encode(['ok' => true, 'data' => $d], $flags);
if ($json === false) { http_response_code(500); echo json_encode(['ok' => false, 'error' => 'Erreur encodage JSON : ' . json_last_error_msg()]); exit; }
echo $json; exit;
}
function gErr($m, $c = 400) { http_response_code($c); echo json_encode(['ok' => false, 'error' => $m]); exit; } function gErr($m, $c = 400) { http_response_code($c); echo json_encode(['ok' => false, 'error' => $m]); exit; }
function gBody() { return json_decode(file_get_contents('php://input'), true) ?? []; } function gBody() { return json_decode(file_get_contents('php://input'), true) ?? []; }