Exception handling problems in php - php

I was trying out PHP exceptions for my project. But it turns out that the exception is thrown successfully but not being caught successfully by the code I wrote.
The code:
try{
require_once(MASTER_PHP."/master_validation.php");
require_once(MASTER_PHP."/master_user.php");
require_once(MASTER_PHP."/master_db.php"); require_once(MASTER_PHP."/master_secure.php");
require_once(MASTER_PHP."/master_ui.php");
require_once(MASTER_PHP."/master_mail.php");
require_once(MASTER_PHP."/master_filehandling.php");
require_once(MASTER_PHP."/master_archive.php");
require_once(MASTER_PHP."/master_date.php");
require_once(MASTER_PHP."/master_social.php");
require_once(MASTER_PHP."/master_message.php");
require_once(MASTER_PHP."/master_gallery.php");
require_once(MASTER_PHP."/master_backup.php");
require_once(MASTER_PHP."/master_payment.php");
require_once(MASTER_PHP."/master_sms.php");
require_once(MASTER_PHP."/master_xml.php");
$filterobj=new ta_filtervalue();
$filterobj->filterrequest();
global $noecho;
if($noecho!="yes")
{
$utilityobj=new ta_utilitymaster();
$utilityobj->includeextassets();
}
}
catch (Exception $e)
{
$custerrcode=$e->getMessage();
$dbobj=new ta_dboperations();
$res=$dbobj->dbquery("SELECT * FROM ".ERROR_CODES." WHERE ".errordb_errcode."='$custerrcode' LIMIT 0,1",DB_ERROR);
$errmsg=$res[0][changesqlquote(errordb_errdesc,"")];
$errpriority=$res[0][changesqlquote(errordb_errpriority,"")];
$errcallback1=$res[0][changesqlquote(errordb_errcallback1,"")];
$errcalltext1=$res[0][changesqlquote(errordb_errcallbacktext1,"")];
$errcallback2=$res[0][changesqlquote(errordb_errcallback2,"")];
$errcalltext2=$res[0][changesqlquote(errordb_errcallbacktext2,"")];
$errtitle=$res[0][changesqlquote(errordb_errtitle,"")];
$errobj=new ta_errorhandle();
$errobj->senderror($errmsg,$custerrcode,$errpriority,$errcallback1,$errcalltext1,$errcallback2,$errcalltext2,$errtitle);
}
If the exception occurs in master_user.php (required file) it has to be caught in the file which requires it. But it does not catch the exception.
The way I throw the exception:
throw new Exception('#ta#0000000_0000000');
where the string inside is the error code.
The error message:
Fatal error: Uncaught exception 'Exception' with message '#ta#0000000_0000000' in
C:\xampp\htdocs\techahoy\securedir\phpmaster\master_user.php:19 Stack trace: #0
C:\xampp\htdocs\techahoy\login\profile.php(4): ta_userinfo->userinit() #1 {main} thrown in
C:\xampp\htdocs\techahoy\securedir\phpmaster\master_user.php on line 19

Looks like (almost) the same as in here.
require() is identical to include() except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script

Related

new mysqli - Why error message will display

I want to check if accessing mysql is possible or not.
I don't wont to have an error message, only true/false if the connection is ready or not.
I tried to do it with this :
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
But always a error message will come up - how can i prevent this message from showing ?
"<b>Fatal error</b>: Uncaught exception 'mysqli_sql_exception' with message 'Access denied for user ''
#'localhost' (using password: NO)' in /is/htdocs/...mypath
.php:33
Stack trace:
#0 /is/htdocs...mypath.myfile.php(33): mysqli->mysqli('', ''
, '', '')
#1 {main}
thrown in <b>/is/htdocs/wp1076647_373QG1K1B0/butobo/module/4/code/cms_checkcon.php</b> on line <b>33
</b><br />"
You need to "catch" this fatal exception via a try/catch statement. This allows you to handle the fatal error and then instead of your script crashing due to it, you can output an error message and exit instead :D
PHP Exceptions: http://php.net/manual/en/language.exceptions.php
I hope this helps.
try
{
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
if ($appDB->connect_error)
{ $res['code']=FALSE; }
else
{
$appDB -> close();
$res['code']=TRUE;
}
}
catch (Exception $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
exit;
}
This will change the ERROR to a WARNING, which will not break your script. From there, if you want to hide everything EXCEPT fatal errors, you can use this line of PHP:
error_reporting(E_ERROR);
Error message would display because your PHP is configured to do so. To make it not display, simply configure it like
ini_set('display_errors', "0");
However, this code also stops the execution. It order to prevent it, you have to catch the exception. So it should be like
try {
$appDB = new mysqli($data[0]['MYSQL']['HOST'], $data[0]['MYSQL']['BENUTZER'], $data[0]['MYSQL']['PW'], $data[0]['MYSQL']['TABELLE']);
$res['code']=TRUE;
}
catch (Exception $e)
{
error_log($e);
$res['code']=FALSE;
}
while setting error_reporting(E_ERROR); is rather stupid as it will prevent you from seeing all other errors

Basic PHP / SOAP error, can't debug

I'm currently having a really frustrating time with some really simple SOAP / PHP at the moment. I've spent about a week trying EVERYTHING I can think of, on multiple different servers with different versions of PHP and they all still throw the same error. Here's the code:
function test() {
$client = new SoapClient('http://xxx', array("login" => "sandbox", "password" => "password"));
print_r($client->__getFunctions());
$ap_param = array();
// it dies here. CheckServiceAvailable is a valid function returned in __getFunctions()
$result = $client->__soapcall('CheckServiceAvailable', $ap_param);
if (is_soap_fault($result)) {
trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
}
}
It faults before the error catching can capture anything. Apache logs show the same fault as below:
Fatal error: Uncaught SoapFault exception: [s:Processing error] in C:\soap.php:13 Stack trace: #0 C:\soap.php(13): SoapClient->__soapCall('CheckServiceAva...', Array) #1 C:\soap.php(23): test() #2 {main} thrown in C:\soap.php on line 13
Without being able to catch the fault I'm totally stuck as to what to do. I don't really want to try nusoap.
Any ideas?
use:
try
{
$result = $client->__soapcall('CheckServiceAvailable', $ap_param);
}
catch (SoapFault $e)
{
echo "Cannot call method CheckServiceAvailable: {$e->getMessage()}";
}

Why do I get an uncaught exception in this code?

So in my code below, I'm not sure where i went wrong. Improper use of syntax, wrong use of variables? Please help!
For some reason i run this in the browser and get back
"Fatal error: Uncaught exception 'numexception' with message 'The numbers are not set' in C:\xampp\htdocs\php_testing\test.php:29 Stack trace: #0 {main} thrown in C:\xampp\htdocs\php_testing\test.php on line 29".
I don't understand where my code went wrong???
class numexception extends Exception{}
function multiply($a,$b){
echo $a*$b;
}
$var1 = 5;
//$var2 = 2; as you can see variable 2 is not set as I commented it out to test
//the exception
if(!isset($var1) or !isset($var2)){
throw new numexception("The numbers are not set");
}
try{
multiply($var1,$var2);
}
catch(numexception $e){
echo "This exception was caught:".$e->getMessage();
}
echo "The script then continues";
The throw is not in the try, so it can't be catched.
What your code is doing is like hitting someone with a golf ball, and then yelling "Fore!".

how to handle HTTPErrorException in php

I am confused in an issue. I have thrown an exception for unauthorized user in a function. When I call this function it shows *Fatal error: Uncaught exception 'HTTPErrorException' *
My code is
throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
How can I catch this Exception so that I can show some CSS instead of the stack trace which is comming
the error code shows that you haven't caught the exception, so it will throw this error. every exception should be caught by your code
try {
....
throw new HTTPErrorException ( 'You are not allowed to access this method.', 401 );
....
} catch (HTTPErrorException $e) {
// generate a stack trace here and show it to user
// you can use $e->getTraceAsString() or $e->getTrace() functions here to get stack trace
}
or if you don't want to use try / catch blocks then you can create a exception handler function that will be called whenever your application has not caught the exception anywhere
function exception_handler($exception) {
echo "Custom Exception: " , $exception->getMessage(), "\n";
}
set_exception_handler('exception_handler');
check more about exceptions http://php.net/manual/en/language.exceptions.php

Handling Exceptions - Fatal error: Uncaught exception 'EppCommandsExceptions' with message 'Command syntax error'

Fatal error: Uncaught exception
'EppCommandsExceptions' with message
'Required parameter missing'
The line in question:
throw new EppCommandsExceptions($result->msg, $codigo);
Why am I having this error on this line?
On EppCommandsExceptions.class.php
I have this class that extends Exception:
class EppCommandsExceptions extends Exception
{
//could be empty.
}
Next, on CommandsController.php I have:
include_once('EppCommandsExceptions.class.php');
and, later, if something bad happens on method1:
throw new EppCommandsExceptions($result->msg, $codigo);
later, on this same controller, another method2 that will run after method1,
I have:
if something goes bad with this too:
throw new EppCommandsExceptions($result->msg, $codigo);
Later I have, for the contact part - method1
try
{
$createdContact = $comandos->createContact($contactoVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
And later, for domain part: method2
try
{
$createdDomain = $comandos->createDomain($domainVo);
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Domain. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Is it because I'm using the same exception for both methods?
Should I have one Exception class for EACH method? :s
Please advice,
Thanks a lot.
MEM
The exception you throw will only be caught if it's inside a try block.
If it isn't it'll propagate up the call stack, until it is caught in one of the earlier calling functions.
You're getting that fatal error because the exception you throw is never caught, so it's handled by the default unhandled exceptions handler, which emits the fatal error.
Examples:
try
{
$createdContact = $comandos->createContact($contactoVo);
if (error_condition())
throw new EppCommandsExceptions $e;
}
catch(EppCommandsExceptions $e)
{
$error .= 'Error Contact. Cód:'.$e->getCode().' Mensagem:'.$e->getMessage();
}
Throwing the exception directly in the try block is not usually very useful, because you could just as well recover from the error condition directly instead of throwing an exception. This construct becomes more useful, though, if createContact may throw an exception. In this case, you have at some point to catch EppCommandsExceptions to avoid a fatal error.

Categories