From 5ac4e51efb7cd6116eeb90b0989d739f0b0eda7e Mon Sep 17 00:00:00 2001 From: perco Date: Mon, 11 May 2026 17:31:29 +0200 Subject: [PATCH] Garage API : gestion d'erreurs robuste (JSON garanti) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 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 --- includes/db.php | 3 ++- modules/garage/api.php | 13 ++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/includes/db.php b/includes/db.php index d2b2259..4226c3c 100644 --- a/includes/db.php +++ b/includes/db.php @@ -35,6 +35,7 @@ try { ); $pdo->exec("SET collation_connection = utf8mb4_general_ci"); } 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()])); } ?> \ No newline at end of file diff --git a/modules/garage/api.php b/modules/garage/api.php index 97971fe..56ee6e5 100644 --- a/modules/garage/api.php +++ b/modules/garage/api.php @@ -6,6 +6,12 @@ header('Content-Type: application/json'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS'); 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'; $UPLOAD_DIR = '/uploads/garage/'; @@ -14,7 +20,12 @@ if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0755, true); } $method = $_SERVER['REQUEST_METHOD']; $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 gBody() { return json_decode(file_get_contents('php://input'), true) ?? []; }