I would like to log the stacktrace of all exceptions thrown caught or uncaught.
Is there a way to do this without having to change every catch method in my application?
Thanks!
You can use set global exception handler so you will get all uncaught exceptions.
You can use the methods from the phps base Exception class.
Use getMessage to get the message Oh no! and use getTraceAsString to get a formatted trace.
refer : Log caught exception with stack trace
You could use https://github.com/php-test-helpers/php-test-helpers to override base exceptions __construct. Just add the 'logging' logic. There is a reason why this package is called test-helpers . I don't recommend using it on production.
Anyway...it is better to rewrite your app :)
Related
I'm missing something really obvious.
How can I make monolog record all php errors, php user errors, and exceptions?
Before using monolog, I wrote my own functions which I passed to set_error_handler(), register_shutdown_function() and set_exception_handler(). Is there a way of doing this using Monolog's API, or do I have to the following?
Write an error handler and exception handler which I pass to PHP's functions above
In those handlers, call the appropriate Monolog functions such as Logger::addError(...) using a switch statement or similar
Surely there must be a Monolog API that does the above in a single call?
From the ErrorHandler class docs:
use Monolog\ErrorHandler;
$logger = new Logger('Logger Name');
ErrorHandler::register($logger);
Old question but since it was not yet answered - ErrorHandler will do exactly what you're after.
From The documentation:
ErrorHandler: The Monolog\ErrorHandler class allows you to easily register a Logger instance as an exception handler, error handler or fatal error handler.
I use die() for error output in a class in PHP.
I sometimes call this class from another class. When the first class dies, I don't want it to kill the class that called it. I think a break() statement within a loop is a good analogy, but instead, I'm looking to break a class from within itself.
Is there a way to confine die() to the class that called it, or is there a preferred way to get this behavior?
Never die() in a class
You can use return, and return an error message, false, etc. Or you can throw an exception.
Galen is right. But I'd go further:
Never use die() for error reporting. Throw an exception - uncaught exceptions get sent to the PHP error log. Or use error_log in conjunction with a custom error/exception handler. Emit proper HTTP headers (500, 404, etc.). Show users a pretty error page.
I was wondering how would one go about writing custom exception handlers.
so that I can do something like
throw new dbException($sql, $message);
and have it output
There was an error in your query
Message: {$message here}
Query: {$sql here}
Line: {line exception was thrown on}
File: {file exception was thrown from}
but I also want to to catch eg syntax errors and parse errors (if possible)
Well, you can extend the Exception class however you like. For custom exceptions, you might want to check out the post:
PHP 5 OOP: Delegation and Custom Exceptions
You should also find this thread useful:
Custom Exception Messages: Best practices
Unless I am misunderstanding your question, you should be able to extend PHP's Exception class.
Why don't use just write your own exception class derived from the standard base exception? See extending exceptions manual.
I am getting my head around PHPUnit, and trying to build a test case for an existing class.
The class is a static configuration class, getting, setting and listing configuration options that will be available in the application.
The class is very strictly built. If I try to set a configuration setting with an incompatible value, or a configuration setting that does not exist, a E_USER_ERROR is thrown, halting the execution of the script. Even if it's not the fine art of error handling, it works fine for the purposes of this class. An error in that class is always the result of a programming error, and never of bad user input.
This has the great advantage that you don't have to worry about how error messages are handled or logged, which keeps the code slim. Output the message (or not, in production), die(), done.
However, with Unit tests, I don't see how I can continue to work with classic PHP errors. I will have to convert the functions to return success flags, or throw exceptions.
Am I correct?
Or is there a way in PHPUnit to expect errors, as there is to expect Exceptions? I can't see any straight away.
From the PHPUnit manual:
By default, PHPUnit converts PHP errors, warnings, and notices that are triggered during the execution of a test to an exception. Using these exceptions, you can, for instance, expect a test to trigger a PHP error as shown in Example 4.8.
class ExpectedErrorTest extends PHPUnit_Framework_TestCase
{
/**
* #expectedException PHPUnit_Framework_Error
*/
public function testFailingInclude()
{
include 'not_existing_file.php';
}
}
Same works for exceptions of course.
Edit: didn't see this was already mentioned in the comments, but I'll leave it here for reference in case someone looks for the same question and doesn't read the comments
If you want to cancel treating warning as Exception, use
PHPUnit_Framework_Error_Warning::$enabled=false; .
I don't know the details of your implementation, but couldn't you raise a normal (custom) exception (which can be tested) and have a global exception handler in your app that will throw the proper E_USER_ERROR based on these (custom) exceptions?
Check set_exception_handler for more information on setting this global exception handler.
Couldn't you define an error handler (via set_error_handler) that will treat any error that cannot be handled by PHPUnit (such as E_USER_ERROR) as a failure of the unit test?
(Inspired by WordPress' tests)
I used to use this when I wanted to trigger errors in PHP, coming from a PHP4 background. Note I had my own set_error_handler() for handling these errors.
if ($error) {
trigger_error('Sorry, error has occured');
}
I can't remember where, but sometime ago someone told me I should be 'using exceptions'. As I'm re factoring a lot of my old code, I figured now is the time to get some good advice on my error handling implementation.
Now that I'm using PHP5 (and a bit smarter than I was when I wrote the older code), is my trigger_error() just an old way of doing things, and if so, what is the best way to handle errors in PHP5?
Yes, you may want to start looking into the PHP 5 exception model. Remember though that just because something is new doesn't mean that you must adopt it. Only adopt those features that you need and make sense in your domain.
That being said, I feel that exceptions are a good concept to grasp and even if you decide not to adopt them you will be all the better for the experience.
I would like to suggest that you read PHP: Exceptions - Manual:
PHP 5 has an exception model similar
to that of other programming
languages. An exception can be thrown,
and caught ("catched") within PHP.
Code may be surrounded in a try block,
to facilitate the catching of
potential exceptions. Each try must
have at least one corresponding catch
block. Multiple catch blocks can be
used to catch different classes of
exeptions. Normal execution (when no
exception is thrown within the try
block, or when a catch matching the
thrown exception's class is not
present) will continue after that last
catch block defined in sequence.
Exceptions can be thrown (or
re-thrown) within a catch block.
I would also encourage you to read What Is an Exception? (Note this is a Java tutorial but the concepts are universal)
When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.
Edit: In order to implement a global exception handler (basically in order to establish a default exception handler that will handle previously unhandled exceptions) you will want to us the set_exception_handler function.
Using exceptions is the object-oriented way to trigger and handle your own application errors.
The PHP manual topic on exceptions is probably a good place to start.
Here is a small example:
function doSomething() {
if ($error) {
throw new Exception('Some descriptive error message.');
}
}
try {
doSomething();
}
catch (Exception $e) {
die('<p class="error">' . $e->getMessage() . '</p>');
}