PHP – Uyarı ve Bilgi Bildirimleri Exception Fırlatsın
PHP’de Uyarı (Warning), Bilgi (Notice) bildirimlerini handle ederken catching yapamamanın eksikliğini yaşamış olabilirsiniz büyük bir ihtimal ile.
set_error_handler ile ister Exception fırlatarak ister fırlatmayarak bu bildirimleri handle edebilirsiniz.
set_error_handler ile Warning ve Notice uyarıları için ayrı ayrı işlemler yapabilirsiniz.
Örneğin:
1 2 3 4 5 6 7 8 9 10 11 12 |
function hatalar($seviye, $mesaj, $dosya, $satir, $detay){ echo $seviye . "\n"; echo $mesaj . "\n"; echo $dosya . "\n"; echo $satir . "\n"; print_r ($detay); } set_error_handler('hatalar'); echo $a; file_get_contents('a'); |
Bir notice bir warning verecek şekilde hatalı yazım yaptım. Böylece handle işlemini yapmış olduk.
Peki nasıl catching yapabiliriz?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
class NotException extends Exception {}//NoticeException class WarException extends Exception {}//WarningException function hatalar($seviye, $mesaj, $dosya, $satir, $detay){ if ($seviye == 8) throw new NotException("Notice!!!"); else if ($seviye == 2) throw new WarException("Warning!!!"); } set_error_handler('hatalar'); try { echo $a; } catch (NotException $e) { echo $e->getMessage(); } try { file_get_contents('a'); } catch (WarException $e) { echo $e->getMessage(); } |
Gördüğünüz gibi artık Try-Catch içinde de işlem yapabiliyoruz.