Funkcija set_exception_handler

Funkcija set_exception_handler ļauj definēt funkciju, kas tiks izsaukta, lai apstrādātu neķertos izņēmumus. Parametrā tiek padots apstrādātāja funkcijas nosaukums vai anonīma funkcija. Apstrādātājs kā parametru saņem izņēmuma objektu.

Sintakse

phpset_exception_handler(callable $exception_handler): callable

Piemērs

Iestatīsim vienkāršu izņēmumu apstrādātāju:

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

Koda izpildes rezultāts:

php'Caught exception: Something went wrong!'

Piemērs

Anonīmas funkcijas izmantošana kā apstrādātāju:

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

Koda izpildes rezultāts:

php'Error: Critical error'

Piemērs

Iepriekšējā apstrādātāja atjaunošana:

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(); // Atjauno firstHandler
  
  throw new Exception('Test');
?>

Koda izpildes rezultāts:

php'First handler: Test'