Php exception stack trace string

PHP Exception getTraceAsString() Method

So, when it catches an Exception, it have to parse the exception stack trace to show function, line arguments, etc. Syntax $exception->getTraceAsString() Technical Details Return Value: Returns a stack trace in the form of a string Related Pages Read more about Exceptions in our PHP Exceptions Chapter.

PHP Exception getTraceAsString() Method

Example

function myFunction($num) <
throw new Exception(«An error occurred»);
>

try <
myFunction(5);
> catch (Exception $e) <
print_r($e->getTraceAsString());
>
?>

Definition and Usage

The getTraceAsString() method returns a stack trace in the form of a string.

Stack traces contain information about all of the functions that are running at a given moment. The stack trace provided by this method has information about the stack at the time that the exception was thrown.

Syntax

Technical Details

Read more about Exceptions in our PHP Exceptions Chapter.

PHP Exception Handling, with message ‘Value must be 1 or below’ in C:\webfolder\test.php:6 Stack trace: #0 C:\webfolder\test.php(12): checkNum(28) #1

thrown in C:\webfolder\test.php on line 6. To create a custom exception handler you must create a special class with functions that can be called when an exception …

Does re-throwing an exception in PHP destroy the stack trace?

In C#, doing the following would destroy the stack trace of an exception :

Because of this, using throw rather than throw e is preferred. This will let the same exception propagate upwards, instead of wrapping it in a new one.

However, using throw; without specifying the exception object is invalid syntax in PHP. Does this problem simply not exist in PHP? Will using throw $e as follows not destroy the stack trace?

When you throw $e in PHP like you did you rethrow the exisiting exception object without changing anything of its contents and send all given information including the stacktrace of the catched exception — so your second example is the correct way to rethrow an Exception in php .

If (for whatever reason) you want to throw the new position with the last message, you have to rethrow a newly created exception object:

throw new RuntimeException( $e->getMessage() ); 

Note that this will not only lose the stack trace, but also all other information which may be contained in the exception object except for the message (e.g. Code , File and Line for RuntimeException ). So this is generally not recommended !

Re-throwing the same exception will not destroy the stack trace. But depending on what you need, you might want to just throw the same exception or build an Exception Chaining ( see PHP Documentation > Exception::__construct )

Читайте также:  How to exit program in java

A very good explanation of when and why one would choose one approach over another is given in this answer

Yes.This is a best way to catch the exception and re-throw the same exception object which carries the stack-trace data. Once you reaches the point of method that handles requests, just catch it there and send response back to user accordingly.

Its a bad idea to throw a new exception object which looses the stack-trace and create an additional object causing memory load.

Try/Catch block in PHP not catching Exception, If you are using a code you don’t know about very well, or — especially — if you are using a framework, it might override the default PHP Exception with one of its own, and therefore you might go to the wrong path and get the undesired result. If you just put \Exception, then you are sure you are catching the base …

What this php stack trace error means?

[05-Mar-2012 02:38:58] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/pokerwor/public_html/request.php:275 Stack trace: #0 /home/pokerwor/public_html/request.php(275): SimpleXMLElement->__construct('') #1 /home/pokerwor/public_html/request.php(295): readXML() #2 thrown in /home/pokerwor/public_html/request.php on line 275 

I have a flash file that sends a xml string to php in an interval. sometimes my php file make this error ,any body knows what is this?

The XML string isn’t valid XML . You should var_dump() the XML output to see what’s wrong with the input. If you want to handle this error to have friendlier output, you can use a try/catch construction:

In the catch code you can also add debugging code, such as writing the XML contents to a log file . This way you won’t have to reproduce the rare situation by ramming your refresh button a hundred times.

Customize Laravel error reporting to remove stack trace,

PHP missing function arguments in exception stack trace

I am working to evolve my own error handler for my php apps and I need to send a pretty Exception report to the user on development server. So, when it catches an Exception, it have to parse the exception stack trace to show function, line arguments, etc. But, I no more have the arguments in function calls.

I think this is caused by XDebug and I tried to change the value of xdebug.collect_params to fix it but without any success. In fact, this config only changes the display of xdebug default report that now have the function call parameters.

I made a test script to test it so I let you see.

\n"; var_dump(ini_get($config)); ini_set($config, 3); function fallDeepToHell($param) < echo 'Param is : ' . $param . "
\n"; throw new Exception(); > try < fallDeepToHell('from heaven'); >catch(Exception $e) < var_dump($e->getTrace()); var_dump($e->getTraceAsString()); > fallDeepToHell('from heaven');

The result on my development server is

Читайте также:  Для удобства создания веб-страниц рекомендуется использовать HTML-редактор

I am using PHP 7.4 with FPM.

max_execution_time = 30 memory_limit = 128M error_reporting = E_ALL display_errors = On display_startup_errors = On html_errors = On post_max_size = 100M upload_max_filesize = 49M date.timezone = Europe/Paris ;[mail function] mail.add_x_header = On ;[Session] session.gc_divisor = 1000 session.gc_maxlifetime = 43200 

My XDebug settings are only about remote things.

I had the same problem, it turned out to be the new zend.exception_ignore_args INI directive introduced in PHP 7.4.

zend.exception_ignore_args is a new INI directive for including or excluding arguments from stack traces generated from exceptions.

PHP cuts off parts of long arguments in exception stack, Update The exact issue we’re having is described in How to disable PHP cutting off parts of long arguments in exception stack trace?. This question can be closed a dupe. This question can be closed a dupe.

Источник

Exception::getTrace

Two important points about this function which are not documented:

1) The trace does not include the file / line at which the exception is thrown; that entry is only recorded in the top-level getFile/Line methods.

2) Elements are returned in ‘closest-first’ order, e.g. if you have a script x which calls function y which calls function z which throws an exception, then the first trace element will be ‘Y’ and the second will be ‘X’.

If you are wanting to see the args within a stack trace on PHP 7.4, note that there is now a zend flag in the php.ini file that is default set to Off.

Set this flag to On and it will show the args again.

The order of the trace starts at the source of the exception and does not include main.
So for example:

function Bar () throw new Exception ;
>

try Foo ();
> catch( Exception $e ) var_dump ( $e -> getTrace ());
>
?>

Will output:

When calling getTrace(), there is also the name of the class in returned array:

throw new Exception ( ‘FATAL ERROR: bla bla. ‘ );

array(1) <
[0]=> array(6) <
[«file»]=> string(54) «/. /test.php»
[«line»]=> int(37)
[«function»]=> string(11) «__construct»
[«class»]=> string(4) «Test»
[«type»]=> string(2) «->»
[«args»]=> array(0) < >
>
>

You can use this function to format a exception:

function MakePrettyException ( Exception $e ) $trace = $e -> getTrace ();

$result = ‘Exception: «‘ ;
$result .= $e -> getMessage ();
$result .= ‘» @ ‘ ;
if( $trace [ 0 ][ ‘class’ ] != » ) $result .= $trace [ 0 ][ ‘class’ ];
$result .= ‘->’ ;
>
$result .= $trace [ 0 ][ ‘function’ ];
$result .= ‘();
‘ ;

echo MakePrettyException ( $e );

Exception: «FATAL ERROR: bla bla. » @ Test->__construct();

Источник

Exception::getTraceAsString

Honestly, Exception::getTraceAsString() simply sucks, listing only the called method (below, for example, on line 89 function fail2() gets called, but there’s no information that you have the originator is fail1()). The fact that, in the example below, the exception gets thrown on line 78, is completely omitted from the trace and only available within the exception. Chained exceptions are not supported as well.

Читайте также:  Text background colors css

Example:
#0 /var/htdocs/websites/sbdevel/public/index.php(70): seabird\test\C->exc()
#1 /var/htdocs/websites/sbdevel/public/index.php(85): seabird\test\C->doexc()
#2 /var/htdocs/websites/sbdevel/public/index.php(89): seabird\test\fail2()
#3 /var/htdocs/websites/sbdevel/public/index.php(93): seabird\test\fail1()
#4

jTraceEx() provides a much better java-like stack trace that includes support for chained exceptions:
Exception: Thrown from class C
at seabird.test.C.exc(index.php:78)
at seabird.test.C.doexc(index.php:70)
at seabird.test.fail2(index.php:85)
at seabird.test.fail1(index.php:89)
at (main)(index.php:93)
Caused by: Exception: Thrown from class B
at seabird.test.B.exc(index.php:64)
at seabird.test.C.exc(index.php:75)
. 4 more
Caused by: Exception: Thrown from class A
at seabird.test.A.exc(index.php:46)
at seabird.test.B.exc(index.php:61)
. 5 more

(see at the end for the example code)

/**
* jTraceEx() — provide a Java style exception trace
* @param $exception
* @param $seen — array passed to recursive calls to accumulate trace lines already seen
* leave as NULL when calling this function
* @return array of strings, one entry per trace line
*/
function jTraceEx ( $e , $seen = null ) $starter = $seen ? ‘Caused by: ‘ : » ;
$result = array();
if (! $seen ) $seen = array();
$trace = $e -> getTrace ();
$prev = $e -> getPrevious ();
$result [] = sprintf ( ‘%s%s: %s’ , $starter , get_class ( $e ), $e -> getMessage ());
$file = $e -> getFile ();
$line = $e -> getLine ();
while ( true ) $current = » $file : $line » ;
if ( is_array ( $seen ) && in_array ( $current , $seen )) $result [] = sprintf ( ‘ . %d more’ , count ( $trace )+ 1 );
break;
>
$result [] = sprintf ( ‘ at %s%s%s(%s%s%s)’ ,
count ( $trace ) && array_key_exists ( ‘class’ , $trace [ 0 ]) ? str_replace ( ‘\\’ , ‘.’ , $trace [ 0 ][ ‘class’ ]) : » ,
count ( $trace ) && array_key_exists ( ‘class’ , $trace [ 0 ]) && array_key_exists ( ‘function’ , $trace [ 0 ]) ? ‘.’ : » ,
count ( $trace ) && array_key_exists ( ‘function’ , $trace [ 0 ]) ? str_replace ( ‘\\’ , ‘.’ , $trace [ 0 ][ ‘function’ ]) : ‘(main)’ ,
$line === null ? $file : basename ( $file ),
$line === null ? » : ‘:’ ,
$line === null ? » : $line );
if ( is_array ( $seen ))
$seen [] = » $file : $line » ;
if (! count ( $trace ))
break;
$file = array_key_exists ( ‘file’ , $trace [ 0 ]) ? $trace [ 0 ][ ‘file’ ] : ‘Unknown Source’ ;
$line = array_key_exists ( ‘file’ , $trace [ 0 ]) && array_key_exists ( ‘line’ , $trace [ 0 ]) && $trace [ 0 ][ ‘line’ ] ? $trace [ 0 ][ ‘line’ ] : null ;
array_shift ( $trace );
>
$result = join ( «\n» , $result );
if ( $prev )
$result .= «\n» . jTraceEx ( $prev , $seen );

return $result ;
>
?>

Here’s the example code:
class A public function exc () throw new \ Exception ( ‘Thrown from class A’ ); // >
>

class B public function exc () try $a = new A ;
$a -> exc (); // >
catch(\ Exception $e1 ) throw new \ Exception ( ‘Thrown from class B’ , 0 , $e1 ); // >
>
>
class C public function doexc () $this -> exc (); // >
public function exc () try $b = new B ;
$b -> exc (); // >
catch(\ Exception $e1 ) throw new \ Exception ( ‘Thrown from class C’ , 0 , $e1 ); // >
>
>

Источник

Оцените статью