Php: exception handling in exception handlers?

Suppose you used custom Exception class extensions to handle custom exceptions, for example, for example:

$testObject = new testClass(); 

and startup:

 function __autoload($class_name) { $file = $class_name.'.php'; if (file_exists($file)) { include $file; }else{ throw new loadException("File $file is missing"); } if(!class_exists($class_name,false)){ throw new loadException("Class $class_name missing in $file"); } return true; } try { $testObject = new testClass(); }catch(loadException $e){ exit('<pre>'.$e.'</pre>'); } 

The testClass.php file does not exist, so loadException is thrown with the message: The testClass.php file is missing. (and all other details ... line number, etc.)

everything was fine until I decided to hide all errors and instead displayed a 404 page (or 500 pages ...), so naturally I thought about adding the loadErrorPage function.

 class loadException { ... function loadErrorPage($code){ $page = new pageClass(); echo $page->showPage($code); } } ... try { $testObject = new testClass(); }catch(loadException $e){ $e->loadErrorPage(500); } 

but this has an obvious problem: if the testClass.php and pageClass.php files are missing, then a fatal error is displayed instead of the preferred 404 page.

I am confused: S How do I elegantly handle this exception in the exception descriptor?

+4
source share
2 answers

If class pageClass does not exist and cannot be loaded by your autoloader $page = new pageClass(); in your method loadErrorPage() will throw another exception. You will have to catch this exception and then do something without this class.

 function loadErrorPage($code){ try { $page = new pageClass(); echo $page->showPage($code); } catch(Exception $e) { // header(...500); echo 'fatal error: ', $code; } } 
+2
source

Well, you can always just not delete pageClass.php ...

I suppose that only one file should not be too complicated to make sure that it does not disappear, just as you make sure that a file in which there is a __autoload function will not go anywhere.

0
source

Source: https://habr.com/ru/post/1309660/


All Articles