Funcția set_exception_handler

Funcția set_exception_handler permite definirea unei funcții care va fi apelată pentru a gestiona excepțiile neprinse. Parametrul transmis este numele funcției-handler sau o funcție anonimă. Handler-ul primește un obiect excepție ca parametru.

Sintaxă

phpset_exception_handler(callable $exception_handler): callable

Exemplu

Să stabilim un handler simplu de excepții:

php<?php
  function myExceptionHandler($exception) {
    echo 'Caught exception: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Something went wrong!');
?>

Rezultatul executării codului:

php'Caught exception: Something went wrong!'

Exemplu

Utilizarea unei funcții anonime ca handler:

php<?php
  set_exception_handler(function($exception) {
    echo 'Error: ' . $exception->getMessage();
  });
  
  throw new Exception('Critical error');
?>

Rezultatul executării codului:

php'Error: Critical error'

Exemplu

Restabilirea handler-ului anterior:

php<?php
  function firstHandler($exception) {
    echo 'First handler: ' . $exception->getMessage();
  }
  
  function secondHandler($exception) {
    echo 'Second handler: ' . $exception->getMessage();
  }
  
  set_exception_handler('firstHandler');
  $old_handler = set_exception_handler('secondHandler');
  restore_exception_handler(); // Restabilește firstHandler
  
  throw new Exception('Test');
?>

Rezultatul executării codului:

php'First handler: Test'