errorexceptiondebuggingkeamananMahir3 mnt baca

Error dan Exception Handling

Menangani kesalahan dengan elegan: error reporting, try-catch, dan bedanya error vs exception.

Melihat error saat development

Saat ngoding di localhost, nyalakan semua laporan error agar bug langsung terlihat:

php
<?php
error_reporting(E_ALL);
ini_set("display_errors", "1");

echo $variabelBelumAda; // langsung muncul warning yang jelas

try-catch: menangkap exception

Banyak operasi (koneksi database, baca file, API) bisa gagal. Bungkus dengan try-catch agar program tidak mati mendadak:

php
<?php
function bagi($a, $b) {
    if ($b == 0) {
        throw new Exception("Pembagi tidak boleh nol!");
    }
    return $a / $b;
}

try {
    echo bagi(10, 0);
} catch (Exception $e) {
    echo "Terjadi kesalahan: " . htmlspecialchars($e->getMessage());
} finally {
    echo "<br>Selesai diproses.";
}

Blok finally selalu jalan, cocok untuk menutup koneksi atau file.

Exception bawaan dan custom

php
<?php
class EmailTidakValidException extends Exception {}

function daftar(string $email): void {
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        throw new EmailTidakValidException("Format email salah: $email");
    }
    echo "Pendaftaran berhasil!";
}

try {
    daftar("bukan-email");
} catch (EmailTidakValidException $e) {
    echo "Validasi gagal: " . htmlspecialchars($e->getMessage());
} catch (Exception $e) {
    echo "Error lain: " . htmlspecialchars($e->getMessage());
}

Catch yang lebih spesifik ditulis lebih dulu, karena PHP memakai catch pertama yang cocok.

Catatan teknis: Di production, matikan display_errors dan nyalakan pencatatan: ini_set("display_errors", "0"); ini_set("log_errors", "1");. Menampilkan error mentah ke pengunjung membocorkan path folder, nama tabel, dan versi software, yaitu bekal gratis untuk penyerang. Tampilkan halaman error ramah ke user, simpan detailnya di log server untuk kamu baca sendiri.