Funktsioon set_exception_handler

Funktsioon set_exception_handler võimaldab määratleda funktsiooni, mida kutsutakse välja püüdmata erandite töötlemiseks. Parameetrina edastatakse töötlejafunktsiooni nimi või anonüümne funktsioon. Töötleja saab erandi objekti parameetrina.

Süntaks

phpset_exception_handler(callable $exception_handler): callable

Näide

Määrame lihtsa erandite töötleja:

php<?php
  function myExceptionHandler($exception) {
    echo 'Püütud erand: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Midagi läks valesti!');
?>

Koodi täitmise tulemus:

php'Püütud erand: Midagi läks valesti!'

Näide

Anonüümse funktsiooni kasutamine töötlejana:

php<?php
  set_exception_handler(function($exception) {
    echo 'Viga: ' . $exception->getMessage();
  });
  
  throw new Exception('Kriitiline viga');
?>

Koodi täitmise tulemus:

php'Viga: Kriitiline viga'

Näide

Eelneva töötleja taastamine:

php<?php
  function firstHandler($exception) {
    echo 'Esimene töötleja: ' . $exception->getMessage();
  }
  
  function secondHandler($exception) {
    echo 'Teine töötleja: ' . $exception->getMessage();
  }
  
  set_exception_handler('firstHandler');
  $old_handler = set_exception_handler('secondHandler');
  restore_exception_handler(); // Taastab firstHandler
  
  throw new Exception('Test');
?>

Koodi täitmise tulemus:

php'Esimene töötleja: Test'