If you have ever worked with CRON jobs that involve getting and parsing data from 3rd party APIs/feeds, you will understand me more than anyone else when I say: handling CRON-related Errors and Exceptions suck. It is inevitable that your script will fail at some point in the future for one of many reason. In my particular case, one of the data providers that I use tends to fail on me. Once my CRON script tries to parse what it perceives to be the retrieved data, an Exception (or an Error) is thrown.
Out of the box LAMP stack offers us two different ways to deal with these unexpected errors:
- File Logging: Have PHP log the error into a file that you later on have to check/review manually.
- CRON Email: LAMP can also utilize the CRON Email functionality to send you or the server administrator an email regarding the Error incident and what caused it.
Unfortunately, these two solutions are rather limiting. What if you want an external API to be notified upon script failure? or perhaps have a record inserted into a SQL DB table with all the possible Error info? these options are currently not available and for that reason I wrote a little library called ScriptCheck.
ScriptCheck is a simple package that allows you to specify a notification method by registering a handler prior to the script’s execution. At the start of the application, ScriptCheck will register itself as the default PHP error handler via
set_exception_handler. Afterwards, the script will continue executing as usual. If an error occurs, the error handler will catch that and notify all handlers/observers.
//Use composer autoloader or your own! require 'vendor/autoload.php'; use Lorenum\ScriptCheck\ScriptCheck; use Lorenum\ScriptCheck\Handlers\FileLoggerHandler; //Instanciate ScriptCheck and add a fileLoggerHandler to be notified $sc = new ScriptCheck(); $sc->addHandler(new FileLoggerHandler("test.log")); $sc->register(); //You application logic goes below here! throw new Exception("Test Exception");
As of right now, ScriptCheck allows for 4 different types of handlers to be registered:
- FileLoggerHandler: Log the error into a file, similar to the standard LAMP stack error logger.
- SQLDBHandler: Insert the error as a row into a SQL DB.
- EmailHandler: Emails the registered person all error details.
- APICallHandler: Calls an external API via POST or GET.
You can actually combine as many of these as you want. You can also extend any of them or implement your own by using the
More information about this package can be found in the Readme file at Github.