Fatal error: Uncaught exception too long - php

I'm using throw new Exception(...) to handle errors, but these errors are huge! With 7 stack traces I get a 5 line error.
Let's say I call for a property that doesn't exist. I want to simply display the property X doesn't exist message, and the location where it was called: in file.php, line Y
Is that possible?

I assume you simply want this for your own personal debugging. You could do a few things:
a) Learn how to read the exception errors
b) Create an exception handler and only output a few things:
set_exception_handler(function(Exception $e)
{
echo $e->getMessage();
// echo out whatever you want to see
die();
});
Reference the docs to see what information is available.
c) Use an extension like xdebug that already provides a pretty exception handler

Use trigger_error and set_error_handler , and you'll be able to know LINE and FILE (in handler function).
Also, in handler you can call debug_backtrace and read all information that you need.

Related

How to make a PHP autoloader throw an error when the autoloaded file has "compile-time" errors (never mind, it already does)

EDIT: It turned out that what I stated in this question was totally wrong. The code was actually turning off error reporting explicitly prior to autoloading, in places where I hadn't found it.
So this question is basically useless. The accepted answer is correct.
In my current configuration, whenever some PHP file has fatal errors such as syntax errors or calling a function that does not exist, I usually get an error message such like:
Parse error: syntax error, unexpected <whatever> in /path/to/file.php on line XXX
or
Fatal error: Call to undefined function whatever() in /path/to/file.php on line YYY
or the like in the very output.
However, I am using third-party libraries which use a third-party autoloader. Whenever there's a fatal error in any of the autoloaded classes (including parse errors or calling unexisting functions - actually not completely sure about the latter but definitely of the parse error case), I just get a blank page, and not only that: no error is even logged in Apache's error_log file, where usually PHP fatal errors would be logged. So debugging becomes impossible.
I can't stress this enough: this only happens when the fatal error is in some autoloaded file. In every other case (including of course errors in files included via require(), include() and the like), the same errors do show up in the output and in the error_log.
I didn't write the autoloader code, but it's basically like this:
// no idea why this line, but I don't think it's relevant:
ini_set('unserialize_callback_func', 'spl_autoload_call');
spl_autoload_register(array('My_Autoloader', 'autoload'), true);
class My_Autoloader {
static function autoload($classname) {
$filename = //.... computes $filename from $classname
require_once($filename);
}
}
There must be a way to have the autoloader throw errors the same way they would be thrown (and handled) if the errors were not in an autoloaded file, right?
How do I get that?
The only way that the code would behave as you suggest is if the third party code is overriding the error reporting. (EDIT by OP: Yep, it turns out it actually was.) That is usually considered good practice for production systems, but it should be logging the error.
That your third party code is causing such errors gives me pause to wonder about its quality, but we'll ignore that for now.
PHP's built in mechanisms will handle the reporting (to the browser) and the logging (to file). Non fatal errors can be managed by your own code after calling set_error_handler() however fatal errors are not handed off via this route. It is possible to trap and handle fatal errors in your own code using register_shutdown_function(). But start by checking your log files.
If, as you say, both error logging and error reporting are disabled, then stop using this third party code - it is toxic.
Syntax Error Check only on Command Line
With php -l somefile.php from PHP
shell_exec('php -l /fullpath/to/somefile.php')
but you have to analyse the respone string for errors.
Normal response No syntax errors detected in somefile.php
In PHP <= 5.0.4 there was php.net/manual/en/function.php-check-syntax.php
Here a fatal error catch that works:
register_shutdown_function(function(){
$err=error_get_last();
if($err['type']===1){
/*you got an fatal error do something, write it to an file*/
#file_put_contents(var_export($err,true),'myfatalerror.log');
}
});
Hope that helps:)
Use php exception so you can call your file into
function inverse($x) {
if (!$x) {
throw new Exception('Division par zéro.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Exception reçue : ', $e->getMessage(), "\n";
}

Preserve Xdebug exception handling when using own exception handler

I've written my own Exception and Error handlers in my PHP project.
However, when doing development, I would like to have XDebug do it's normal "exception" and "error" handling in addition to my own.
I've found that I can easily enough have XDebug continue to do "error" handling if my own error handler returns FALSE. But I can't find a way to get a similar effect with "Exception" handling.
I was hoping I could manually call an XDebug function. xdebug_print_function_stack() is the closest thing I could see, but it won't give a true stack trace of the triggered exception.
Xdebug adds a property to every thrown Exception, namely xdebug_message, which contains the contents of the table normally displayed by Xdebug.
So to visualize an exception with stacktrace as Xdebug, you could do something like the following:
try {
$result = fetch();
}catch(Exception $e){
echo '<table>' . $e->xdebug_message . '</table>';
}
And while searching for the documentation of xdebug_message I stumbled on a possible duplicate question: Methods for an Xdebug Exception class

PHP Fatal error: Uncaught exception 'Exception'

I'm playing around with exceptions in PHP. For example, I have a script that reads a $_GET request and loads a file; If the file doesn't exists, an new exception should be thrown:
if ( file_exists( $_SERVER['DOCUMENT_ROOT'] .'/'.$_GET['image'] ) ) {
// Something real amazing happens here.
}
else {
throw new Exception("The requested file does not exists.");
}
The problem is that, when I try to supply an non existent file for the test, I got a 500 error instead of the exception message. The server log is the following:
[09-Jul-2013 18:26:16 UTC] PHP Fatal error: Uncaught exception 'Exception' with message 'The requested file does not exists.' in C:\sites\wonderfulproject\script.php:40
Stack trace:
#0 {main}
thrown in C:\sites\wonderfulproject\script.php on line 40
I wonder if I'm missing something real obvious here.
I've checked this question PHP fatal error: Uncaught exception 'Exception' with message but it's not quite like my issue, and have no concise answer.
Help, please?
* EDIT *
It seems this is something related to the throw keyword. If I use echo for example, I got the message printed on the screen, like this:
exception 'Exception' with message 'The file does not exists.' in C:\sites\wonderfulproject\script.php:183 Stack trace: #0 {main}
Why is that?
** EDIT 2 **
Thanks to #Orangepill, I got a better understanding about how to handle exceptions. And I found a superb tut from nettuts that helped a lot. The link: http://net.tutsplus.com/tutorials/php/the-ins-and-outs-of-php-exceptions/
This is expected behavior for an uncaught exception with display_errors off.
Your options here are to turn on display_errors via php or in the ini file or catch and output the exception.
ini_set("display_errors", 1);
or
try{
// code that may throw an exception
} catch(Exception $e){
echo $e->getMessage();
}
If you are throwing exceptions, the intention is that somewhere further down the line something will catch and deal with it. If not it is a server error (500).
Another option for you would be to use set_exception_handler to set a default error handler for your script.
function default_exception_handler(Exception $e){
// show something to the user letting them know we fell down
echo "<h2>Something Bad Happened</h2>";
echo "<p>We fill find the person responsible and have them shot</p>";
// do some logging for the exception and call the kill_programmer function.
}
set_exception_handler("default_exception_handler");
Just adding a bit of extra information here in case someone has the same issue as me.
I use namespaces in my code and I had a class with a function that throws an Exception.
However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.
Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.
For
throw new Exception('test exception');
I got 500 (but didn't see anything in the browser), until I put
php_flag display_errors on
in my .htaccess (just for a subfolder).
There are also more detailed settings,
see Enabling error display in php via htaccess only

Facebook PHP SDK Throwing an Uncatchable OAuthException

I'm attempting to post an open graph action to the Facebook Graph API but receiving an OAuth Exception (#3501) User is already associated to the <object>. That's all well and good, I expect Facebook to throw that exception. I get some other exceptions regarding authenticating a user (maybe with old/stale sessions, whatever).
My question is, has anyone else experienced that this exception is uncatchable in php? In this specific example (of posting graph actions) I am absolutely wrapping the call to the api in a try/catch statement; but I still get the fatal error.
<?php
try {
//publishing to open graph
$this->fb->api('/me/app:action', 'POST', array(
'object' => 'http://www.domain.com/path/to/graph/object',
));
}
catch (Exception $e)
{
/*
We may get here if the user has already posted this action before...
or if our session somehow went sour
or bc facebook is down...
or one of any other 1000 reasons the graph api is currently
sucking...
in any case it doesn't much matter, this is not a mission critical
thing to worry about; if we don't post the graph action - we don't
post the graph action..nbd.
*/
}
The above code is the snippet the publishes the graph action (generalized, because the content of it isn't important to this example).
I realize that the Exception that the Facebook PHP SDK is throwing is a FacebookApiException but that class extends Exception. I can't for the life of me figure out why in the name of all things logical, I can't catch my exception like this.
Has anyone experienced this issue? Is this a bug in the FB PHP SDK? Am I missing something else here? Thanks for your help!
Also, for reference, the relevant parts of the FB PHP SDK are here:
FacebookAPIException Definition (base_facebook.php line 30)
Throwing OAuthException (base_facebook.php line 1105
Edit 5/1/12
After some more investigation, it turns out that this "Exception" isn't really being treated like an exception at all. Typical Exceptions print out a stack trace back to the method call which resulted in throwing the exception. These "OAuthExceptions" do not. Also, typical exceptions pring out their error string a bit differently, for example:
PHP Fatal error: Uncaught exception 'Exception' with message 'foo' /path/to/file.php:10
or
PHP Fatal error: Uncaught exception 'MyException' with message 'stupid php' /path/to/file:10
#0 /path/to/file.php(17): doTest()
#1 {main}
thrown in /path/to/file.php on line 10
In this particular case, we don't get any of that, and it looks much more like a typical fatal error:
PHP Fatal error: Uncaught OAuthException: (#3501) User is already associated \
to the <object> object on a unique action type <action>. Original Action ID: \
123123123
thrown in /path/to/app/libs/fb/base_facebook.php on line 1107, \
referer: http://www.domain.com/path/to/page
I can't make any sense of why this forsaken "Exception" is so weird/uncatchable.
The Solution:
I figured out the answer to my own question; I've added it below - it's developer error, not a bug. The answer is below.
Also, this very well could be part of a bug, if you wanted to say that being able to reference a class definition as a type-hint to the catch definition which didn't exist (or wasn't available in the current namespace) is a bug.
So, something that's not outline above is that I'm utilizing PHP namespaces. This is a big gotchta since namespaces are relatively new to php, it's super easily overlooked I feel. Regardless, it's a pretty silly oversight/error.
If you're in a defined namespace (that is, not the root (\) namespace) you don't have direct access to the Exception class. Instead of php throwing a warning about not knowing what that class is, it just ignores the fact that it doesn't know what it is - and doesn't catch the exception.
Solution 1:
import the exception class:
<?php
use \Exception;
// ...codes
try {
//...codes
}
catch (Exception $e)
{
//...codes
}
Solution 2:
provide the full path to the exception class:
<?php
try {
//.....
}
catch (\Exception $e)
{
// voila.
}

Best possible PHP error class

I am looking for some coding ideas on the following task I am trying to achive.
I have a list of Error Numbers, Description, and User Friendly Description in a document.
Ex:
Error Number, Description, User Friendly Description
-----------------------------------------------------
1, Internal Error, "An Internal Error has occurred. Please try again later".
2, Delete Failed, "Unable to delete an Entry. Please try later".
I want to write a PHP class to store all the above in such a fashion that I can access them later with ease when an error occurs in the code..
Ex: If my code received an error 2, I want to check that error code with the list of error codes in the class, retrieve the description, user friendly description and display it to the user.
I want this to be of minimum overhead. So, don't want to store it in database.
I am using PHP5 with Zend MVC framework. Anybody can help me with the best possible sample code?
Thanks
Write an ini file with the error code and the user friendly text.
write an class which extends Exception which fetches your errorcodes from the ini file. add a method e.g.
public function getUserFriendlyMsg(){}
which returns the string from the ini file.
in your normal code when you have such an error you just need to throw the exception. e.g.
throw new My_Exception('Delete failed',2);
in your e.g. controller:
try{
// your code
}catch(My_Exception $e){
echo $e->getUserFriendlyMsg();
}
Note: you should consider extending your excpetion class to log the failures to a logfile, for this you can introduce servity levels. (see the manual - exception handling)
I like to use a simple custom error handler and custom exception handler that do the following:
If in development mode:
Show the detailed error message
If E_WARNING or worse, output error message into a log file (e.g. using Zend_Log)
If a fatal error, halt execution and show a nice error page with a full backtrace
If in production mode:
Only log error messages
On fatal errors, halt execution and show a nice "an error has occurred" page only.
I like working with errors, so any exception I catch I call a trigger_error() for to do the output and logging.
You can also extend the default Exception class to do the logging and display. You would want to turn any error that occurs into exceptions. Manual errors you would then trigger as exception using throw.
Inspiration:
Kohana's Error Handler (Screenshot here) is the nicest and greatest I've seen to date. It's open source, maybe you can even grab out that part (make sure you read the license first, though.)

Categories