简体   繁体   中英

How do I catch an imagick fatal error in PHP

i am using imagick to create thumbnails for pdf documents. i get a fatal error on this line..

$imagick->readImage($file .'[0]');

I tried wrapping in a try catch but as i learned that doesn't work because it's a fatal error, not an exception. How would I gracefully catch this error?

I am more concerned about using PHP to detect the error than solving the imagick problem, since any number of errors might come up with user pdf files. thanks!

Unfortunately it's not possible to catch fatal errors in php. This is given. There are still couple of things you can do:

  1. Function registered using register_shutdown_function() is still executed. You can put your error hadling into such function, and if the readImage() succeeds, register empty function.

  2. You can put thumbnail generation into php command line script and execute it using exec('php thngenerate.php ' . escapeshellarg($file .'[0]'), $out, $return_var); . If $return_var != 0 , there was an error.

  3. Similar to #2, but script is called using http, this time you watch for internal server error.

It should show up in the server error logs which can give you insight into why it fails and hopefully prevent it from happening in the first place. Other than that, it depends on what you are trying to do. I use mine for resizing images and creating thumbnails so my checks are related to that; does imagick show the correct dimensions and is the thumbnail present and have a file size greater than 0.

You can set your custom error handler with set_error_handler :

function exceptionErrorHandler($errno, $errstr, $errfile, $errline ) {    
    throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exceptionErrorHandler");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM