Reputation: 1769
I'm using the PHP Exceptions with many try/catch blocks and all works fine, except in one specific snippet.
See the codes below:
Controller.class
<?php
namespace Controller;
use Business\Exceptions\AppException;
use Business\OTA\Responses\Erros\RS_ERROR;
use Utils\Merge;
class Controller{
//other methods
public main(){
//do stuff
$resp = $this->merge($con)
}
private function merge($con)
{
try {
$merge = new Merge($this->record, $con);
$merge->sortResponses();
return $merge->searchResponse;
} catch (AppException $ex){
$response = new RS_ERROR($this->client);
echo ($response);
}
}
}
Merge.class (simplified)
<?php
namespace Utils;
use Business\Exceptions\AppException;
use Exception;
class Merge
{
public $responses;
public $conectors;
public $searchResponse;
/**
* Method __construct
* @param array $conectorResponses
* @param $conectors
* @throws \Business\Exceptions\AppException
*/
public function __construct(array $conectorResponses, $conectors)
{
$this->responses = $conectorResponses;
$this->conectors = $conectors;
$this->searchResponse = array();
if (empty($this->responses)) {
$ex = new AppException("Search Not found", '11');
throw $ex;
}
}
When I run the code and the call Merge constructor, even when $this->responses
is empty, the Exception is thrown, but it is not catched in the Controller and I see the notice
PHP Notice: Trying to get property of non-object in /var/www/ws-test/app/Controller/Controller.class.php on line 96
Refers to the line return $merge->searchResponse;
When I debug the code, I can use a breakpoint in throw $ex
, but this is not catched.
Am I doing something wrong? Why the exception is ignored?
I see some similar questions here in SO, but any describe the same problem.
Upvotes: 0
Views: 204
Reputation: 45500
Something is not correct in your code:
$this->searchResponse = array();
then you return an empty array:
return $merge->searchResponse;
perhaps you meant:
return $merge->responses;
To make sure you catch all exception, catch all your custom ones first then add Exception
on the last catch block:
try {
//code
} catch (AppException $ex){
$response = new RS_ERROR($this->client);
echo ($response);
}catch (Exception $e){
var_dump($e);
}
Upvotes: 1