Well readable error? - php

If i have a c1.php
<?php
class C1 {
function f1($value) {
if($value == 'ok') {
echo "OK!";
} else {
throw new Exception("WRONG!");
}
}
}
?>
and index.php
<?php
require_once('c1.php');
$c = new C1();
$c->f1('ok');
$c->f1('asd');
?>
Can anybody know, how to construct a well readable error message like "Error: you have wrong value in C:\xampp\htdocs\projekt\index.php: line 5" instead of tracktracing
OK!
Fatal error: Uncaught exception 'Exception' with message 'WRONG!' in
C:\xampp\htdocs\projekt\c1.php:7 Stack trace: #0
C:\xampp\htdocs\projekt\index.php(5): C1->f1('asd') #1 {main} thrown in
C:\xampp\htdocs\projekt\c1.php on line 7
that reading is a little difficult.

Catch the exception. This is the point of exceptions.. they are catchable and you can do something with the information (for instance.. output just the message).

You can do something like this:
try {
$c = new C1();
$c->f1('ok');
$c->f1('asd');
} catch(Exception $e) {
echo 'Error: you have wrong value in ', $e->getFile(), ' on line ', $e->getLine();
// ... code
}

i caught it
try {
..
} catch(Exception $e) {
//echo $e->getTraceAsString();
$t = $e->getTrace();
$t = $t[0];
echo 'Error: file - ',$t['file'],' - line: ',$t['line'],
' - function: ',$t['function'],'; ',$e->getMessage();
}
thank you for hints.

Simple, don't use an exception. They should be used when you're doing a try-catch or for an exceptional situation. This is not exceptional - meaning nothing can possibly turn an error with just a if-else statement.
So just echo out the error message of your choice.

Related

$exception->getTraceAsString() first item missing

I throw an exception inside Ă  file.php I want to catch and display the trace for debugging, but the trace is incomplete when I get it with $exception->getTraceAsString(). The trace is correct when I use debug_print_backtrace() inside the exception constructor:
# page.php, called by index.php
<?php
class CustomException extends Exception {
public function __construct($message = "", $code = 0, $previous = null) {
echo '<pre>';
debug_print_backtrace();
echo '</pre>';
parent::__construct($message, $code, $previous);
}
}
try {
include('file.php'); // throw a CustomException
} catch (CustomException $e) {
echo '<pre>' . $e->getTraceAsString() . '</pre>';
echo '<hr>';
echo '</pre>';
}
# output of debug_print_backtrace():
#0 App\Exception… called at [/path/to/file.php:1396]
#1 include(/path/to/file.php) called at [/path/to/page.php:3]
#2 require_once(/path/to/page.php) called at [/path/to/index.php:100]
# output of $e->getTraceAsString():
#0 /path/to/page.php(3): include()
#1 /path/to/index.php(100): require_once('/path/to/i...')
#2 {main}
Is there a way to get the full traceAsString (and more important for me, the output of $e->getTrace()) ?
getTrace()/getTraceAsString() seems to be just the trace, but not the error message. You can always build your own line, which can also help with readability. I use something like this on a lot of my logging, which is useful even when I don't include the trace:
$error_string = "Error with (whatever it is), ".$e->getMessage() . " on " . $e->getLine() . " of " . $e->getFile();
You can also check to see what kind of exception it might be:
$error_string .= " - Exception of type ".get_class($e);

How to check if included file from a loop comes with errors

I have this kind of loop. On each iteration it should include a file, Included files can come with errors. Once some of included files gets an error the whole process of getting lost. How to prevent breaking of the process?
I tried this try catch but it errors from included files still cause stopping execution of file.
Thanks
foreach ($li_arrays as $index => $li_array) {
if($index == 0){
try {
require 'update.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
elseif ($index == 1){
try {
require 'update1.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}else{
try {
require 'update2.php';
} catch(Exception $e) {
echo "Exception caught with message: " . $e->getMessage() . "\n";
}
}
Errors in php are not recoverable, so they will always lead to the termination of your script.
I am not even sure that you are even talking about Errors, though if you are, this is the answer to your question.
Another thing to be aware of:
Require will throw an E_COMPILE_ERROR if the required file doesn't exist, which is also something you won't be able to catch.
If you don't want to terminate if the script isn't found, use include instead.
At the end I changed "require" with "include" and used this try-catch approach inside each included file.
$attempts = 0;
do {
try
{
////PHP code ///
} catch (Exception $e) {
echo "\n\n======EXCEPTION======\n\n";
var_dump($e);
$attempts++;
sleep(30);
continue;
}
break;
} while($attempts < 5);

How to catch require_once/include_once exception?

I'm trying to write code similar this:
<?php
$includes = array(
'non_existing_file.php', //This file doesn't exist.
);
foreach ($includes as $include) {
try {
require_once "$include";
} catch (Exception $e) {
$message = $e->getMessage();
echo "
<strong>
<font color=\"red\">
A error ocurred when trying to include '$include'.
Error message: $message
</font>
</strong>
";
}
}
I'd tried require_once and include_once, but try catch doesn't catch the exception.
How could I catch this fatal errors/warning exceptions?
Since include/require does not throw an exception, check before if the file your want to include exists and is readable. eg:
$inc = 'path/to/my/include/file.php';
if (file_exists($inc) && is_readable($inc)) {
include $inc;
} else {
throw new Exception('Include file does not exists or is not readable.');
}
These functions are throwing E_COMPILE_ERROR, and are not catchable like this.
To handle these errors see set_error_handler.
This solution (adapted from here) worked fine to me:
register_shutdown_function('errorHandler');
function errorHandler() {
$error = error_get_last();
$type = $error['type'];
$message = $error['message'];
if ($type == 64 && !empty($message)) {
echo "
<strong>
<font color=\"red\">
Fatal error captured:
</font>
</strong>
";
echo "<pre>";
print_r($error);
echo "</pre>";
}
}

Facebook showing fatal error in php sdk

What is meant by the below error?Why am i getting this.
Fatal error: Uncaught Exception: 601: Parser error: unexpected end of query. thrown in base_facebook.php on line 1039
I'm using a code to delete the invite once the user clicks on it from app tab,but this is not deleting the app request
Here is the code,
foreach ($request_ids as $request_id)
{
echo ("reqeust_id=".$request_id."<br>");
$full_request_id = build_full_request_id($request_id, $user_id);
echo ("full_request_id=".$full_request_id."<br>");
try {
$delete_success = $facebook->api("/$full_request_id",'DELETE');
if ($delete_success) {
echo "Successfully deleted " . $full_request_id;}
else {
echo "Delete failed".$full_request_id;}
}
catch (FacebookApiException $e) {
echo "error";}
}
Why is this bit in quotes?
$facebook->api("/$full_request_id",'DELETE');
Surely it should just be:
$facebook->api($full_request_id,'DELETE');
Other than that I see nothing wrong with your code. Although, it would be good to know what line 1039 in base_facebook.php is.

php - How to catch an unexpected error?

I'm writing a script, where a lot of things could go wrong. I'm making if/else statements for the obvious things, that could heppen, but is there a way to catch something, that could possible heppen, but I don't know what it is yet?
For example something causes an error of some kind, in the middle of the script. I want to inform the user, that something has gone wrong, but without dozens of php warning scripts.
I would need something like
-- start listening && stop error reporting --
the script
-- end listening --
if(something went wrong)
$alert = 'Oops, something went wrong.';
else
$confirm = 'Everything is fine.'
Thanks.
Why not try...catch?
$has_errors = false;
try {
// code here
} catch (exception $e) {
// handle exception, or save it for later
$has_errors = true;
}
if ($has_errors!==false)
print 'This did not work';
Edit:
Here is a sample for set_error_handler, which will take care of any error that happens outside the context of a try...catch block. This will also handle notices, if PHP is configured to show notices.
based on code from: http://php.net/manual/en/function.set-error-handler.php
set_error_handler('genericErrorHandler');
function genericErrorHandler($errno, $errstr, $errfile, $errline) {
if (!(error_reporting() & $errno)) {
// This error code is not included in error_reporting
return;
}
switch ($errno) {
case E_USER_ERROR:
echo "<b>My ERROR</b> [$errno] $errstr<br />\n";
echo " Fatal error on line $errline in file $errfile";
echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")<br />\n";
echo "Aborting...<br />\n";
exit(1);
break;
case E_USER_WARNING:
echo "<b>My WARNING</b> [$errno] $errstr<br />\n";
break;
case E_USER_NOTICE:
echo "<b>My NOTICE</b> [$errno] $errstr<br />\n";
break;
default:
echo "Unknown error type: [$errno] $errstr<br />\n";
break;
}
/* Don't execute PHP internal error handler */
return true;
}
$v = 10 / 0 ;
die('here');
Read up on Exceptions:
try {
// a bunch of stuff
// more stuff
// some more stuff
} catch (Exception $e) {
// something went wrong
}
throw new Exception('Division by zero.');
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
http://php.net/manual/en/language.exceptions.php
You should definitely use the try-catch syntax to catch any exception thrown by your script.
Additionally you can extend exceptions and implement new ones that fulfill your needs.This way, you can throw your own exceptions when you find any other kind of unexpected error (error for your script's logic).
A very short example explaining the use of extending exceptions :
//your own exception class
class limitExceededException extends Exception { ... }
try{
// your script here
if($limit > 10)
throw new limitExceededException();
}catch(limitExceededException $e){//catching only your limit exceeded exception
echo "limit exceeded! cause : ".$e->getMessage();
}catch(Exception $e){//catching all other exceptions
echo "unidentified exception : ".$e->getMessage();
}
Besides using try/catch, I think it's important to consider if you should catch an unexpected error. If it's unexpected then your code has no idea how to handle it and allowing the application to continue may produce bad data or other incorrect results. It may be better to just let it crash to an error page. I just recently had a problem where someone had added generic exception handlers to everything, and it hid the original location of the exception making the bug difficult to find.

Categories