ZF1 Get errors before redirect - php

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();
}

Related

How to manage exceptions in multiple nested functions?

I am learning how to use Exceptions in PHP. In a subfunction of my code, I want to throw an Exception to stop the main function if an error appears.
I have three functions:
function main_buildt_html(){
...
check_if_parameters_are_ok();
// if the subfunction_check exception is thrown, don't execute the process below and go to an error page
...
}
function check_if_parameters_are_ok(){
...
try{
...
subfunction_check();
...
}catch(Exception $e){
}
...
}
function subfunction_check(){
...
if ($some_error) throw new Exception("Its not ok ! stop the process and redirect the user to an error page");
...
}
From my main "main_buildt_html" function, how can I properly detect if an exception has been thrown?
I want to detect the "subfunction" exception from the main function so I can stop the standard process and redirect the user to an error HTML page.
Normally the exception will be throwin up until the highest level in the chain, or when you catch it in any level.
in your case, if you want to catch the exception in check_if_parameters_are_ok() and main_buildt_html() functions, you need to throw the exception up in the check_if_parameters_are_ok() function.
function check_if_parameters_are_ok(){
...
try{
...
subfunction_check();
...
}catch(Exception $e){
//handle exception.
throw $e; // throw the excption again
}
}
now you need to catch the excption in the main_buildt_html() function.
function main_buildt_html(){
try {
check_if_parameters_are_ok();
} catch (Exception $e) {
// handle the excption
}
}
check_if_parameters_are_ok() should return false when it catches the error. The main function should test the value.
function main_buildt_html(){
...
if (check_if_parameters_are_ok()) {
...
} else {
...
}
}
function check_if_parameters_are_ok(){
...
try{
...
subfunction_check();
...
}catch(Exception $e){
return false;
}
...
}

I can not catch exception in Yii framework

I am using Yii framework and have written code below. When there is no entry for a specific id it gives Error: Call to a member function delete() on a non-object which is a yii\base\ErrorException indicated in debug mode. The problem is that I am not able to catch this exception despite my inclusion of yii\base\ErrorException and specify it catch block. What is the problem here?
use yii\base\ErrorException;
try {
$model = BranchUser::findOne($_GET['id']);
$model->delete();
return $this->redirect(['index']);
} catch (ErrorException $e) {
return $this->redirect(['site/error']);
// Error, rollback transaction
throw $e;
// print_r($model->getErrors());
}
That is a fatal error and it is not possible to recover from it.
You should check that $model is something else than null before you try to use it.
if ($model === null) {
return $this->redirect(['site/error']);
}
Such errors are catchable in PHP 7.0, so that's good.

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);
}

PHP SOAP Second request doesn't throw an exception

i am trying to connect to a webservice. My webserviceHelper is:
class webserviceHelper {
public function __construct($params) {
$this->service_url = $params['service_url'];
try {
$this->soap = new SoapClient($this->service_url,
array('exceptions' => true));
}
catch (SoapFault $exc) {
echo 'SoapFault<br />';
die;
}
catch (Exception $exc) {
echo 'Exception<br />';
die;
}
}
...
}
When the service is down, i make a request to the page where the webserviceHelper object created. Before the response i make second request to the same page. At first one, i got "soapFault" as output but at the second, i got a fatal error.
Fatal error: SOAP-ERROR: Parsing WSDL: Couldn't load from 'WebService?wsdl' : failed to load external entity "WebService?wsdl" in webserviceHelper.php on line 40
How can i prevent this error?
use error_get_last() after $this->soap = new SoapClient(..... to get potential errors
I handled it by using a hook in codeigniter. Thanks to the blogger. How To Catch PHP Fatal Error In CodeIgniter

Get all the exceptions from one try catch block

I wonder if it's posible to get all the exceptions throwed.
public function test()
{
$arrayExceptions = array();
try {
throw new Exception('Division by zero.');
throw new Exception('This will never get throwed');
}
catch (Exception $e)
{
$arrayExceptions[] = $e;
}
}
I have a huge try catch block but i want to know all the errors, not only the first throwed. Is this possible with maybe more than one try or something like that or i am doing it wrong?
Thank you
You wrote it yourself: "This will never get throwed" [sic].
Because the exception will never get thrown, you cannot catch it. There only is one exception because after one exception is thrown, the whole block is abandoned and no further code in it is executed. Hence no second exception.
Maybe this was what the OP was actually asking for. If the function is not atomic and allows for some level of fault tolerance, then you can know all the errors that occurred afterwards instead of die()ing if you do something like this:
public function test()
{
$arrayExceptions = array();
try {
//action 1 throws an exception, as simulated below
throw new Exception('Division by zero.');
}
catch (Exception $e)
{
//handle action 1 's error using a default or fallback value
$arrayExceptions[] = $e;
}
try {
//action 2 throws another exception, as simulated below
throw new Exception('Value is not 42!');
}
catch (Exception $e)
{
//handle action 2 's error using a default or fallback value
$arrayExceptions[] = $e;
}
echo 'Task ended. Errors: '; // all the occurred exceptions are in the array
(count($arrayExceptions)!=0) ? print_r($arrayExceptions) : echo 'no error.';
}

Categories