Continue the execution code after a Fatal Error - php

I use imagick to create thumbnails of PDF files, but in some cases imagic returns a Fatal Error.
I am looking for a way to know when the fatal error occurs.
Something like this:
function MakeThumb($source) {
if($im = new imagick($source)) {
//Generate thumbnail
return($thumb);
} else {
return 'no_thumb.png'; // then we will not tray again later.
}
}

You could do something like this
function MakeThumb($source) {
try {
//throw exception if can't create file
if(!$im = new imagick($source) {
throw new Exception('Count not create thumb');
}
//ok if got here
return($thumb);
} catch (Exception $e) {
return 'no_thumb.png';
}
}
I haven't tested it,but by using Try Catch, you can make it work
http://php.net/manual/en/language.exceptions.php

Related

Laravel 5.3 Intervention/image NotReadableException using images from urls

How do I deal with the following error so that my script doesn't stop working when the exception occurs:
NotReadableException in AbstractDecoder.php line 302: Image source not
readable
I've tried using the following ($file is the url of the image):
// Return false if error
try
{
$img = Image::make($file);
}
catch(NotReadableException $e)
{
return false;
}
This doesn't seem to catch the exception and return false. What else can I do?
You either need the full namespaced exception in the catch area or add the use statement for that exception at the top of the file
Add Intervention\Image\Exception\NotReadableException:
use Intervention\Image\Exception\NotReadableException;
try {
//
} catch(NotReadableException $e) {
//
}

php try catch not working properly

I have code like this:
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = file_get_contents($nbg_xml_url);
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}`
and problem is that, when file_get_contents can not read url (may be site not responding or something like this..) my code writes error: failed to open stream: HTTP request failed! and execution goes direct to finally block bypass catch block without entering in it..
any ideas?
You can set an empty error handler to prevent the warning and afterward throw a custom exception in case of failure. In this case I would write a custom file_get_content like so:
function get_file_contents($url) {
$xml_content = file_get_contents($url);
if(!$xml_content) {
throw new Exception('file_get_contents failed');
}
return $xml_content;
}
and would use it in your block:
set_error_handler(function() { /* ignore errors */ });
try {
$providerError = false;
$providerErrorMessage = null;
$nbg_xml_url = "http://www.somesite.com/rss.php";
$xml_content = get_file_contents($nbg_xml_url); //<----------
// ... some code stuff
} catch (Exception $e) {
$providerError = true;
$providerErrorMessage = $e -> getMessage();
$usd = 1;
$rate = null;
$gel = null;
} finally {
// .. Write in db
}
Then remember to restore the error handler calling:
restore_error_handler();
Note that when using your own error handler it will bypass the
error_reporting
setting and all errors included notices, warnings, etc., will be passed to it.
$xml_content = file_get_contents($nbg_xml_url);
The function file_get_contents does not throw an exception. Thus an exception will not be thrown if as you say the file is not found.
From the docs:
An E_WARNING level error is generated if filename cannot be found...
This function returns the read data or FALSE on failure. So you could check if $xml_content is FALSE ($xml_content === false) and proceed accordingly.
This is a php code for catching any error or exception.
Throwable is the base interface for any object that can be thrown via a throw statement, including Error and Exception.
This will catch fatal errors too. Without throwable it will not catch fatal errors.
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Executed only in PHP 7, will not match in PHP 5.x
} catch (Exception $e) {
// Executed only in PHP 5.x, will not be reached in PHP 7
}

How can I check if file exists with exception handeling

I am trying to use exception handling in case a file does not exists. For example when I run the model method and pass a string usr (which I know there is no file with that name) . It gives me the following error message
Fatal error: Uncaught exception 'Exception' with message 'Usr.php was not found' in /app/core/controller.php on line 14
I can't figure out whats wrong here. Can someone please help me figure this out?
Below is my code. Thanks alot!
class Controllers{
public function model($model){
if(!file_exists("../app/models/".$model.".php")) {
throw new exception("{$model}.php was not found");
}
try {
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
You can't throw an exception without catching it; this automatically causes the PHP script to crash. So, you need to surround your entire function in the try-catch block, or the "model not found" exception will be uncaught. Your code should be something like this:
<?php
class Controllers {
public function model($model){
try {
if (!file_exists("../app/models/".$model.".php")) {
throw new Exception("{$model}.php was not found");
}
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
Never mind guys! I found out I needed to use the try/catch blocks in the file where my method is being invoked
Example..
class Home extends Controllers{
public function index($name = ""){
try{
$user = $this->model('Usr');
}catch (Exception $e){
echo $e->getMessage();
}
//var_dump($user);
}

ZF1 Get errors before redirect

As the title says, I want to get all errors before the redirect. So this is my case:
I have a select for changing databases(identical structure but different data);
So let's say I am here: localhost/user/edit/id/100 (database 1)
on db change, I am redirecting the user to the same page, but we load data from database 2.
If it is not found, I get an error:
"Fatal error: Call to a member function on a non-object ..."
How do I catch the errors before the redirect occurs in order to change the url?
Thanks!
Use try {} catch() {} for catching errors before redirect.
try {
if (/* if error occured */) {
throw new \Exception('Error occured');
}
} catch(\Exception $e) {
// redirect with error occured
}
// redirect without error
In Zend maybe need to use return $redirectObj, I don't know Zend well.
In your case, try to do this:
try {
if ( ! $this->getResponse()) {
throw new Exception('Error occured! Can not get response object');
}
return $this->getResponse()->setRedirect($url);
} catch (Exception $e) {
echo $e->getMessage();
die();
}

Cleanest way to execute code outside of try block only if no exception is thrown

This question is about the best way to execute code outside of try block only if no exception is thrown.
try {
//experiment
//can't put code after experiment because I don't want a possible exception from this code to be caught by the following catch. It needs to bubble.
} catch(Exception $explosion) {
//contain the blast
} finally {
//cleanup
//this is not the answer since it executes even if an exception occured
//finally will be available in php 5.5
} else {
//code to be executed only if no exception was thrown
//but no try ... else block exists in php
}
This is method suggested by #webbiedave in response to the question php try .. else. I find it unsatisfactory because of the use of the extra $caught variable.
$caught = false;
try {
// something
} catch (Exception $e) {
$caught = true;
}
if (!$caught) {
}
So what is a better (or the best) way to accomplish this without the need for an extra variable?
One possibility is to put the try block in a method, and return false if an exception is cought.
function myFunction() {
try {
// Code that throws an exception
} catch(Exception $e) {
return false;
}
return true;
}
Have your catch block exit the function or (re)throw/throw an exception. You can filter your exceptions as well. So if your other code also throws an exception you can catch that and (re)throw it. Remember that:
Execution continues if no exception is caught.
If an exception happens and is caught and not (re)throw or a new one throw.
You don't exit your function from the catch block.
It's always a good idea to (re)throw any exception that you don't handle.
We should always be explicit in our exception handling. Meaning if you catch exceptions check the error that we can handle anything else should be (re)throw(n)
The way I would handle your situation would be to (re)throw the exception from the second statement.
try {
$this->throwExceptionA();
$this->throwExceptionB();
} catch (Exception $e) {
if($e->getMessage() == "ExceptionA Message") {
//Do handle code
} elseif($e->getMessage() == "ExceptionB Message") {
//Do other clean-up
throw $e;
} else {
//We should always do this or we will create bugs that elude us because
//we are catching exception that we are not handling
throw $e;
}
}

Categories