Funzione set_exception_handler

La funzione set_exception_handler consente di definire una funzione che verrà chiamata per gestire le eccezioni non catturate. Il parametro accetta il nome della funzione di gestione o una funzione anonima. Il gestore riceve l'oggetto eccezione come parametro.

Sintassi

phpset_exception_handler(callable $exception_handler): callable

Esempio

Impostiamo un semplice gestore di eccezioni:

php<?php
  function myExceptionHandler($exception) {
    echo 'Eccezione catturata: ' . $exception->getMessage();
  }
  
  set_exception_handler('myExceptionHandler');
  
  throw new Exception('Qualcosa è andato storto!');
?>

Risultato dell'esecuzione del codice:

php'Eccezione catturata: Qualcosa è andato storto!'

Esempio

Utilizzo di una funzione anonima come gestore:

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

Risultato dell'esecuzione del codice:

php'Errore: Errore critico'

Esempio

Ripristino del gestore precedente:

php<?php
  function firstHandler($exception) {
    echo 'Primo gestore: ' . $exception->getMessage();
  }
  
  function secondHandler($exception) {
    echo 'Secondo gestore: ' . $exception->getMessage();
  }
  
  set_exception_handler('firstHandler');
  $old_handler = set_exception_handler('secondHandler');
  restore_exception_handler(); // Ripristina firstHandler
  
  throw new Exception('Test');
?>

Risultato dell'esecuzione del codice:

php'Primo gestore: Test'