Error and exception handling in php7 - php

Recently moved to php7. The following error occurs:
argument 1 passed to MyClass\Throwable::exceptionHandler() must be an instance of Exception, instance of Error given
And the respective class
namespace MyClass;
class Throwable
{
public function exceptionHandler(\Exception $exception)
{
//logic here
}
}
As stated in docs
most errors are now reported by throwing Error exceptions.
Does it mean that I have to provide an instance of Error or even more general Throwable to the exception handler?

Errors and Exceptions both extend Throwable however Errors are not extended from Exception.
Therefore, your ExceptionHandler must accept an object of Type Throwable in order to accept Errors.
Simplest fix is this, though you may want to rename $exception to make it clear.
namespace MyClass;
class Throwable
{
public function exceptionHandler(\Throwable $exception)
{
//logic here
}
}
Note: The new Error class should not be confussed with an ErrorException which has classicly been used as a device for turning PHP 5 errors into Exception objects with symantic meaning.
http://php.net/manual/en/class.error.php

Related

How does Throwable interface work inside catch ()?

Interfaces cant be instantiated , and interfaces do not have methods bodys so how that code works ? (to manage Exception and Error at same time in php 7 we use Throwable cause Exception and Error both implement a new interface )
try {
// Code that may throw an Exception or Error.
} catch (Throwable $t) {
// Handle exception
}
Exception and Error implement the interface Throwable. In fact there is a whole hierarchy for Errors in PHP. You can catch a specific type of error or you can go up the tree and catch more generic errors. Throwable is the base interface and is going to catch all errors in the hierarchy.
When type hinting with OOP you do not need to use the exact type. You can use the base interface or parent type. For example.
interface MyInterface {
}
class A implements MyInterface {
}
function doSomething(MyInterface $obj) {
// something
}
doSomething(new A);
This code works and accepts the object of class A even if the type expected is an interface MyInterface.

What's the difference in the output of two different PHP versions (i.e. PHP 5.6.30 and PHP 7.1.0) after applying the empty index operator on a string? [duplicate]

Recently moved to php7. The following error occurs:
argument 1 passed to MyClass\Throwable::exceptionHandler() must be an instance of Exception, instance of Error given
And the respective class
namespace MyClass;
class Throwable
{
public function exceptionHandler(\Exception $exception)
{
//logic here
}
}
As stated in docs
most errors are now reported by throwing Error exceptions.
Does it mean that I have to provide an instance of Error or even more general Throwable to the exception handler?
Errors and Exceptions both extend Throwable however Errors are not extended from Exception.
Therefore, your ExceptionHandler must accept an object of Type Throwable in order to accept Errors.
Simplest fix is this, though you may want to rename $exception to make it clear.
namespace MyClass;
class Throwable
{
public function exceptionHandler(\Throwable $exception)
{
//logic here
}
}
Note: The new Error class should not be confussed with an ErrorException which has classicly been used as a device for turning PHP 5 errors into Exception objects with symantic meaning.
http://php.net/manual/en/class.error.php

Exception not being caught inside object method

This is more just for documentation, since I've already solved the issue, but it was subtle and difficult enough to debug that I thought it would be useful in the public sphere.
The issue was that I had a try/catch block in an object method that just wasn't working. The reduced example is in two files, which look like this:
TestClass.php:
<?php
//TestClass.php
namespace MyTest;
class TestClass {
public function __construct() {
\e("Initializing object");
try {
\e("Trying object exception");
\throwTestException("Failing gracefully in object");
\e("After exception");
} catch (Exception $e) {
\e($e->getMessage());
}
\e("After object init exception");
}
}
?>
Main.php:
<?php
//Main.php
function e($str) { echo "\n$str"; }
function throwTestException($msg) {
throw new RuntimeException($msg);
}
require "TestClass.php";
e("Beginning");
try {
e("First try");
throwTestException("Failing gracefully first");
e("After exception");
} catch (Exception $e) {
e($e->getMessage());
}
e("Ending");
e('');
e('Beginning object test');
new \MyTest\TestClass();
e('Ending object test');
?>
The expected result on loading Main.php was this:
Beginning
First try
Failing gracefully first
Ending
Beginning object test
Initializing object
Trying object exception
Failing gracefully in object
After object init exception
Ending object test
What I actually got was something like this:
Beginning
First try
Failing gracefully first
Ending
Beginning object test
Initializing object
Trying object exception
Fatal Error: Uncaught Exception: Failing gracefully in object......
As you can see, the exception was not being caught. I tried all sorts of things and just couldn't figure out why it wasn't being caught. And then.... (See answer below)
I realized it was a namespace issue. Because I had declared TestClass within the namespace MyTest, and throwTestException in the global namespace, my reference to Exception within the class method was tacitly resolving to \MyTest\Exception and thus NOT matching the actual exception being thrown, \RuntimeException. And since I wasn't actually trying to instantiate the exception from within the namespace, no "Unknown Class" errors emerged to reveal what was happening.
The solution, then, was simply to properly resolve the exception class I was trying to catch:
catch(\Exception $e) { .... }
To be fair, this became obvious as I built my highly reduced example. It wasn't obvious initially because the exception I was expecting to catch was being generated by the class's superclass (which was the SQLite3 class). Thus, I didn't have to worry about the namespace when generating the exception, and all I was thinking about when catching it was to use the most general form of exception, Exception. And again, since I wasn't instantiating that exception -- only matching against it in a catch block --, I didn't get any notices that it was unresolved.

Exceptions don't bubble through instances in PHP?

I was getting an error about an exception thrown in a __toString() method in a class of mine, even though there was a try...catch() in there. I did some tracking down and it turns out an object within my instance was throwing an exception in its __toString(), which meant that it wasn't being caught by the containing class' catch!
I wrote some test code as a demonstration:
class test {
public function __toString() {
try {
$b = new b();
echo (string)$b;
} catch (exception $e) {
return (string)$e;
}
}
}
class b {
public function __toString() {
throw new Exception ("test");
}
}
$test = new test();
echo $test;
I had thought that exceptions always "bubbled up" through the code until they were caught or made it all the way out.
Is there any workaround for this? The instance within my class is from a library; I don't know if I can maintainably modify it to have a catch in its own __toString().
Per PHP's __toString() section in the magic methods docs:
Warning
You cannot throw an exception from within a __toString() method. Doing
so will result in a fatal error.
When executing the code snippet you gave you get a message that says the same thing:
PHP Fatal error: Method b::__toString() must not throw an exception
There's a feature request here to support this, which states that in current state of things it would be hard to implement.
Having said all that, the proper way to fix this is to submit a patch to your upstream library to not throw exceptions from that method.
If that's not possible, the workaround for you is instead of:
echo (string)$b;
write
echo $b->__toString();
In which case you can catch the exception as you expect.

What is $previous in Exception class?

What does $previous in the Exception constructor argument denote? How could I use it?
class MyException extends \Exception {
private $message;
private $code;
public function __construct($message,$code,\Exception $previous=null){
$this->message = $message;
$this->code = isset($code) ? $code : 0;
parent::__construct($message,$code,$previous);
}
}
I didn't find anything in the API Doc
If you throw an exception because you caught an exception, you can add the original exception as $previous. That means you can actually "nest" exceptions:
try {
throw new FooException('Foo exception');
} catch (FooException $e) {
$code = 1;
throw new BarException('Bar exception', $code, $e);
}
You can then loop over the exception "stack" instead of just the exception caught, providing you with more context.
while($e instanceof \Exception) {
echo $e->getMessage();
$e = $e->getPrevious();
}
Now, you would probably use this if you're implementing a library that can throw an exception, but you'd like to wrap that exception in your own. That way, your clients' code only needs to know of your exceptions, and not that of the exceptions that the dependencies of your code has, while not losing any kind of information.
the reason is that PHP 5.3 introduces nested exceptions as a default part of the PHP base Exception class. While the above code will work, if you are utilizing PHP 5.3, you can pass any previous exception as a third argument , and use the Exception::getPrevious() method to get a previously raised exception.
argument of a previous exception, allowing you to nest the exceptions. When preparing to log your exception, you can opt to iterate through any possible previously thrown and nested exceptions, and log any of the data you need.
What is nesting? Nesting is the ability to catch a particular exception, create a new exception object to be thrown with a reference to the original exception. This then allows the caller access to both the exception thrown from within the consumed library of the more well known type, but also access to the exception that originated this exceptional behavior as well.
Why is this useful? Typically, this is most useful in code that consumes other code that throws exceptions of its own type. This might be code that utilizes the
for more
http://www.brandonsavage.net/exceptional-php-nesting-exceptions-in-php/

Categories