I'm trying to test a try/catch block using a stub that throws an exception when a certain method create is called. It works fine, the exception is raised, but instead of my application catching it, it stops the execution of the test. What is some better ways to go about doing this.
<?php
// TestCase
$mockDao->expects($this->once())
->method('create')
->will($this->throwException(new \Exception));
$service->addEntity($data);
?>
<?php
// Service
public function addEntity($data)
{
....
try {
...
$this->create($entity); // Test Halts with Exception
...
} catch (Exception $e) {
// Never Gets Called
$this->handleException($e);
}
}
You are throwing \Exception but catching Exception. Is the class that implements addEntity() in a namespace? Does changing it to catch \Exception fix the problem? If not, try changing the test to throw Exception.
Related
Suppose I have a repository class, a service class, and finally a controller class.
Now, I have a repository class that uses PDO, and I enclosed the execution into a try-catch block, example, below:
MyRepository {
public function someRepositoryFunction()
{
try {
...some pdo execution
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
My question is, when I call that someRepositoryFunction() in the Service class, do I have to enclose it in a try-catch block also? example, below:
MyService {
public function someServiceFunction()
{
$repo = new MyRepository();
try {
$repo->someRepositoryFunction();
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
}
and finally, when I call the Service class in the Controller, do I also have to enclose the someServiceFunction() in a try-catch block?
Or, catching it in the Repository class enough?
When you catch an Exception, you got 2 options, manage the Exception right were you caught it, according to your app logic or needs or you can throw the exception again and propagate this Exception.
In your case you are throwing the exception again, so you need to catch it again in whatever place you called the method and if you keep throwing the exception up you have to keep catching it.
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.
I want to catch a specific Exception and handle it properly. However, I have not done this before and I want to do it in the best way.
Will it be correct to create a separate class something like
class HandleException extends Exception
{
//my code to handle exceptions;
}
and in it have different methods handling the different exception cases? As far as I understand, the Exception class is like an "integrated" class in php so it can be extended and if an Exception is caught it is not obligatory to terminate the flow of the program?
And, an instance of this class will be created when an exception is caught? Sth. like
catch ( \Exception $e ) {
$error = new HandleException;
}
You CAN extend the basic Exception object with your own, to provide your own exception types, e.g.
class FooExcept extends Exception { .... }
class BarExcept extends Exception { .... }
try {
if ($something) {
throw new FooExcept('Foo happened');
} else if ($somethingelse) {
throw new BarExcept('Bar happened');
}
} catch (FooExcept $e) {
.. foo happened, fix it...
} catch (BarExcept $e) {
... bar happened, fix it ...
}
If an Exception is caught, then the program DOESN'T necessarily have to abort. That'd be up to the exception handler itself. But if an exception bubbles always back up to the top of the call stack and ISN'T caught, then the entire script will abort with an unhandled exception error.
From the manual
Multiple catch blocks can be used to catch different classes of
exceptions. Normal execution (when no exception is thrown within the
try block) will continue after that last catch block defined in
sequence. Exceptions can be thrown (or re-thrown) within a catch
block.
So you can do something like this:
try {
// some code
} catch ( HandleException $e ) {
// handle sthis error
} catch ( \Exception $e ) {
// handle that error
}
This will handle different exceptions. You can also use the finally keyword with newer versions of PHP.
I have a code like this one:
public function one()
{
try {
$this->two();
} catch (Exception $E) {
$this->three();
}
}
How can i test that $this->three() function is called?
I've tried to "mock by code" $this->two() and throw error instead of it's original code, but that ends up with error caught by phpunit itself.
Tried setExpectedException, but it also doesn't solve the problem - catch runs inside phpunit again and just ignored.
Function $this->three() never called in both cases.
Thanks!
The problem was that the described method were in a class which was placed in a namespace containing it's own Exception implementation. So I was catching an \Namespace\Exception while throwing an \Exception.
Throwing correct exception did the thing.
#sectus, thank you!
I want to catch an exception that is thrown by the Google API PHP library, but for some reason it generates a 'Fatal error: uncaught exception' before reaching my catch block.
In my app I have something like this:
try {
$google_client->authenticate($auth_code);
} catch (Exception $e) {
// do something
}
This is Google_Client's authenticate():
public function authenticate($code)
{
$this->authenticated = true;
return $this->getAuth()->authenticate($code);
}
The authenticate($code) above is Google_Auth_OAuth2::authenticate(), which at some point throws the exception:
throw new Google_Auth_Exception(
sprintf(
"Error fetching OAuth2 access token, message: '%s'",
$decodedResponse
),
$response->getResponseHttpCode()
);
If I put a try/catch block in the Google_Client's authenticate, it catches the exception, but without it the program just dies instead of reaching the main try/catch block from my app.
As far as I know this shouldn't be happening. Any ideas?
The problem was that the try/catch block was in a namespaced file and PHP requires you to use "\Exception". More info: PHP 5.3 namespace/exception gotcha
Example (taken from the link above):
<?php
namespace test;
class Foo {
public function test() {
try {
something_that_might_break();
} catch (\Exception $e) { // <<<<<<<<<<< You must use the backslash
// something
}
}
}
?>
I'm not sure how the structure of Google's API is, and I'm not a real fluent PHP programmer, but you're catching a specific exception type of Exception, with which Google's Google_Auth_Exception may not inherit from.
Therefore, since your try-catch block is looking for an exception that is a member of Exception and the Google_Auth_Exception is perhaps not a member of Exception, then your try catch block will miss it.
Try catching the specific exception. This has happened to me before in many different languages.
Edit
The link you posted inherits its exception from: Google/Auth/Exception
Google/Auth/Exception inherits its exception from: Google/Exception
Google/Exception extends Exception, which may, in this context be the Exception that your class is referring to.
It seems my justification for your try-catch block not catching an exception is completely wrong, but the wisdom could still be true. Try catching the specific exception, then use instanceof to see if PHP recognizes Google_Auth_Exception as a member of Exception.