How do I catch an imagick fatal error in PHP

做~自己de王妃 提交于 2019-12-12 01:59:43

问题


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!


回答1:


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.




回答2:


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.




回答3:


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");


来源:https://stackoverflow.com/questions/28156447/how-do-i-catch-an-imagick-fatal-error-in-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!