JSON Error / Exception Messages in Codeigniter 2.0+
09 Apr 2012
One of my recent projects required me to build a quick JSON only API to abstract interaction with multiple databases for multiple web applications, as I'd already got some of the logic in Codeigniter I just added Phil Sturgeon's Codeigniter REST Library. However while this handles all method not found errors when URL routing gets as far as the controller all other errors still appear as HTML, when using curl and attempting to parse as JSON this isn't helpful.
My solution was to extend the core Exceptions class which normally deals with these errors. This is done by creating MY_Exceptions.php in application/core and using something similar to the code below:
This code will only output a basic JSON formatted message, it will not vary the http error codes based on conditions, nor will it take into account accepts headers or similar. Right now this class meets my needs but features such as other formats could easily be added.