Capturing PHP errors and Exceptions

5

Scenario

I know that I can set up the logs for errors and exceptions to be written, that's cool, but sometimes it's too boring to read these files.

Question

  • How to catch Errors and Exceptions in order to be able to handle them at runtime?
  • What impact might this have on the performance of my application?
  • Objective

    There is an online system that interacts with the app, captures errors, and shows them on a website ( link ). The idea is to make a in-house ployment similar.

      

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

        
    asked by anonymous 28.01.2014 / 20:58

    1 answer

    4

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

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

    In this way, you can handle any uncaught exception. To handle the 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 logarExcecao($e) method you can define what you will do when you receive an exception. Remember that you should not take actions in this method that are very computationally expensive, as this can compromise the usability of your system. Accessing a text file to write to it will probably be faster than accessing a DB with PDO , for example. In this case, you can define a routine, for example, every 30min, send a report via email, via cron jobs.

    You said that you did not want to, but still, for more robust LOG solutions, I recommend the monolog library, which can be inserted into the project via Composer.
    28.01.2014 / 21:38