Forráskód Böngészése

Add serverError function and refactor error handling

Alejandro Rosales 1 éve
szülő
commit
d00d2f86c5
2 módosított fájl, 37 hozzáadás és 16 törlés
  1. 22 0
      action/error.php
  2. 15 16
      dependencies.php

+ 22 - 0
action/error.php

@@ -0,0 +1,22 @@
+<!DOCTYPE html>
+<html lang="en">
+
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>Error del servidor</title>
+    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@picocss/pico@1/css/pico.min.css">
+</head>
+
+<body>
+    <main class="container">
+        <article>
+            <header>
+                <h1><?= $title ?></h1>
+            </header>
+            <p><?= $message ?></p>
+        </article>
+    </main>
+</body>
+
+</html>

+ 15 - 16
dependencies.php

@@ -65,40 +65,39 @@ returnResponse(500, $exception->getTraceAsString(), true, 'Internal Server Error
 returnResponse(404, null, true, 'The requested resource was not found.');
 */
 
+// Function server error
+function serverError($title, $message)
+{
+    header('Content-Type: text/html');
+    http_response_code(500);
+
+    require "{$_SERVER['DOCUMENT_ROOT']}/action/error.php";
+    exit();
+}
+
 // DOTENV: load environment variables from .env file
 try {
     $dotenv = Dotenv\Dotenv::createImmutable($_SERVER['DOCUMENT_ROOT']);
     $dotenv->load();
 } catch (Dotenv\Exception\InvalidPathException $e) {
-    header('Content-Type: application/json');
-    http_response_code(500);
-
-    echo json_encode(array(
-        'error' => $e->getMessage(),
-        'mensaje' => 'No se pudo cargar el archivo .env en la raiz del proyecto'
-    ));
-
+    serverError('Error de configuración', 'No se pudo cargar el archivo de configuración');
     exit();
 }
 
 // POSTGRES: load PostgresDb class
 use \SeinopSys\PostgresDb;
 
-function makeConnection($hostOrConnectionString, $port = null, $dbname = null, $user = null, $password = null): PostgresDb {
+function makeConnection($hostOrConnectionString, $port = null, $dbname = null, $user = null, $password = null): PostgresDb
+{
     $connectionString = is_null($port) ? $hostOrConnectionString : "pgsql:host=$hostOrConnectionString;port=$port;dbname=$dbname;user=$user;password=$password";
-    
+
     try {
         $pdo = new PDO($connectionString);
         $db = new PostgresDb();
         $db->setConnection($pdo);
         return $db;
     } catch (PDOException $e) {
-        header('Content-Type: application/json');
-        http_response_code(500);
-        echo json_encode([
-            'error' => $e->getMessage(),
-            'mensaje' => "No se pudo conectar a la base de datos" . (is_null($dbname) ? "" : " $dbname")
-        ]);
+        serverError('Error de conexión', 'No se pudo conectar a la base de datos');
         exit();
     }
 }