Add error handling to API for better debugging on Plesk

- writeData now returns JSON error if file write fails
- Global error/exception handler returns JSON instead of blank 500

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-08 12:33:54 +02:00
parent 30d57c80c0
commit 68ee03ba21

20
api.php
View File

@@ -5,6 +5,14 @@
*/ */
session_start(); session_start();
header('Content-Type: application/json; charset=UTF-8'); header('Content-Type: application/json; charset=UTF-8');
set_error_handler(function($severity, $message, $file, $line) {
throw new ErrorException($message, 0, $severity, $file, $line);
});
set_exception_handler(function($e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage(), 'file' => basename($e->getFile()), 'line' => $e->getLine()]);
exit;
});
// ─── VAIHDA TÄMÄ SALASANA! ────────────────────────────────────── // ─── VAIHDA TÄMÄ SALASANA! ──────────────────────────────────────
define('ADMIN_PASSWORD', 'passus'); define('ADMIN_PASSWORD', 'passus');
@@ -31,10 +39,18 @@ function readData(string $file, $default = []) {
} }
function writeData(string $file, $data): void { function writeData(string $file, $data): void {
file_put_contents( $path = DATA_DIR . $file;
DATA_DIR . $file, $dir = dirname($path);
if (!is_dir($dir)) @mkdir($dir, 0755, true);
$result = @file_put_contents(
$path,
json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
); );
if ($result === false) {
http_response_code(500);
echo json_encode(['error' => "Tiedoston kirjoitus epäonnistui: $file (kansio: " . (is_writable($dir) ? 'kirjoitettava' : 'EI kirjoitettava') . ")"]);
exit;
}
} }
function ok($data = []): void { function ok($data = []): void {