Capture errors and PHP Exceptions

Asked

Viewed 717 times

5

Setting

I know I can configure the logs so that the errors and exceptions are recorded, this is nice, but sometimes it is too boring to read these files.

Question

  1. How to capture the mistakes and exceptions in order to be able to manipulate them at execution time?
  2. What impact this can have on the performance of my application?

Goal

There is an online system that interacts with the application, captures errors and shows them on a website (http://bugsnag.com). The idea is to make an implementation in-house similar.

Do not respond with indications from other similar systems. the question has scope in the implementation of such functionality, and not in the use of a third party system.

  • You want to capture them to do what to them? If it is to debug, it is often important to know what the server was doing when the error happened. Personally, I think more difficult do it when logs are separated and I have to keep both open at the same time and keep comparing timestamps (e.g. access.log and the error.log Apache). Regardless, I consider your question valid.

1 answer

4


You can capture your exceptions like this with set_exception_handler():

function exceptionHandler($e) {
    Notificador::logarExcecao($e);
    throw $e;
}
set_exception_handler('exceptionHandler');

This way, you can manipulate any unforeseen exception. To manipulate errors, use set_error_handler(), which works similarly. If you need a more specific control, you can put it in the exception constructor, something like this:

class LogException extends Exception {
    public function __construct($message = null, $code = 0) {
        parent::__construct($message, $code);
        Notificador::logarExcecao($this);
    }
}

Your other exceptions will only extend this LogException.

In the method logarExcecao($e) you can define what you will do when receiving an exception. Remember that you should not do actions in this method that are very expensive computationally, since this can compromise the usability of your system. Accessing a text file write to it will probably be faster than accessing a DB with PDO, for example. In this case, you can set a routine, for example every 30 minutes, send a report by email, via cron Jobs.


You said you didn’t want to, but still, for more robust LOG solutions, I recommend the library monolog, which can be inserted into the project via Composer.

  • Yes Calebe, I know the Monolog and I find it super interesting, however the focus of the question was to show how is the PHP interface for third party logs

  • If you look at bugsnag documentation, you will find that he uses the same methods I used.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.