12

I am trying to handle some errors in my api. However I tried some so many ways to execute what it's needed to it done?

In the code i used Exception, \Exception, another class extending to Exception, "use \Exception". None of these options works. What i need to do execute the block catch?

  //Piece of source in the begin of file
    namespace Business\Notifiers\Webhook;
    use \Exception;
    class MyException extends \Exception {}

    //Piece of source from my class
    try{

        $products = $payment->getProducts();
        if(count($products) == 0)
            return;
        $flight_id = $products[0]->flight_id;
        $this->message = 'Sir, we have a new request: ';
        $products = null; //Chagind it to null to force an error..
        foreach($products as $product){

            $this->appendAttachment(array(
                'color' => '#432789',
                'text' => 
                    "*Name:* $product->name $product->last_name \n" . 
                    "*Total Paid:*  R\$$product->price\n",
                'mrkdwn_in' => ['text', 'pretext']
            ));
        }
    } catch(Exception $e){
        $this->message = "A exception occurred ";
    } catch(\Exception $e){
        $this->message = "A exception occurred e";
    } catch(MyException $e){
        $this->message = "A exception occurred";
    } 
4
  • You need to actually throw an exception... Commented Oct 15, 2016 at 21:09
  • throw new Exception('throwing an exception...'); secure.php.net/Exceptions Commented Oct 15, 2016 at 21:11
  • I'm forcing the exception. I changed the $products to null, after this line im using foreach. Commented Oct 15, 2016 at 21:12
  • This does not throw an exception (or fatal error), it's a warning. Warning: Invalid argument supplied for foreach() Commented Oct 15, 2016 at 21:13

2 Answers 2

24

The accepted answer above give the real cause of the issue, but did not answer the topic

If in case someone is interested and is looking for

what is the difference between Exception and \Exception inside a namespace?

Still valid against PHP 7.3.5:

  1. \Exception: Refer to Exception in root namespace
  2. Exception: Refer to Exception in current namespace
  3. PHP does not fall back to root namespace, if the class cannot be found in current name space, it emits an error.

<?php
namespace Business;
try {
    throw new Exception("X"); //  Uncaught Error: Class 'Business\Exception' not found
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}

<?php
namespace Business;
class Exception extends \Exception {} // means \Business\Exception extends \Exception

$a = new Exception('hi'); // $a is an object of class \Business\Exception
$b = new \Exception('hi'); // $b is an object of class \Exception
Sign up to request clarification or add additional context in comments.

2 Comments

Further clarification can be found at stackoverflow.com/a/44867502/2511355. If you haven't extended the global Exception class, you should choose use \Exception
6

First of all, you need to understand the difference between an exception and an error:

  1. http://php.net/manual/en/language.exceptions.php
  2. http://php.net/manual/en/ref.errorfunc.php

Trying to foreach over a null value will not yield an exception, but trigger an error. You can use an error handler to wrap an error in an exception, as such:

<?php

function handle ($code, $message)
{
    throw new \Exception($message, $code);
}

set_error_handler('handle');

// now this will fail
try {
    $foo = null;
    foreach ($foo as $bar) {
    }
} catch(\Exception $e) {
    echo $e->getMessage();
}

However in your code, you can simply check if $products is null and if so, throw an exception:

if (!$products) {
    throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...

2 Comments

Foreaching over a NULL value will not trigger an error. PHP throws a warning.
Deep down, a warning is just an error with E_WARNING level. The code will work either way. You can monitor for only certain types of errors by specifying the second parameter of the set_error_handler() function - php.net/manual/en/function.set-error-handler.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.