4

I build some api endpoint, and trying to work on logging exception, so I purposely remove database and run the endpoint to get PDOException.

My question is, if I did not caught the exception, when I ran the endpoint through postman, it shows me a much more detailed message, stack trace, etc (about 1000 lines),

but if I caught the exception with try catch block something like this

catch (\Exception $exception) {
    print_r($exception->__toString());
    print_r("\n\n");

    die;
}

It is so much less details. Why is that? and is there anyway to print the same exact data that we got when we don't caught the exception?

8
  • 1
    The $exception object holds a lot more information than is rendered by the magic __toString() method, just take a look at the actual object methods and properties like getTrace() Commented May 11, 2016 at 18:00
  • Look into debug_backtrace(). As for the reason why, is that Xdebug is probably enabled, which is a PHP extension that will loop through the results of that function to give you a stack trace. Commented May 11, 2016 at 18:00
  • And you don't need to call __toString() explicitly; the whole point of the magic method is that it's called implicitly (magically) if you try to echo the object Commented May 11, 2016 at 18:01
  • @NickJ - no need to use debug_backtrace(); the Exception object already holds the stack trace information Commented May 11, 2016 at 18:03
  • @MarkBaker so is there anyway I can do smtg like print_r($exception)? I want the same details as when the exception is not caught so I can log it. Commented May 11, 2016 at 18:25

2 Answers 2

4
+50

You have all that data. Exception object has many methods:

try {
    // something throwing exception
} catch (\Exception $e) {
    echo $e->getCode() . "\n";
    echo $e->getFile() . "\n";
    echo $e->getLine() . "\n";
    echo $e->getMessage() . "\n";
    echo $e->getTraceAsString() . "\n";
}

Read more about Exception class:
http://php.net/manual/en/class.exception.php

Sign up to request clarification or add additional context in comments.

5 Comments

This still does not give as much details as, if the exception is not caught.
What details are you missing?
is $e->getMessage() also truncated?
nevermind, I think my updated question is a bit different from my original question
$e->getMessage() seems to be truncated to 32Kb
1

You can always throw the exception in the catch block, and let PHP handle. This will let you do something with the exception, then continue the default behavior.

catch (\Exception $exception) {
    // Do something with the exception

    throw $exception;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.