I'd like to catch both errors and exceptions in my Silex app to wrap them in a custom JSON response that will always be returned to clients. I've found three basic methods:
$app->error()
Symfony\Component\Debug\ErrorHandler::register();
Symfony\Component\Debug\ExceptionHandler::register();
While I'm able to catch controller exceptions using error() I'm failing with php errors- they always end up in xdebug.
I'm also failing to understand how error() and ExceptionHandler::register() interact with each other- do I need both? How can I make sure my error() response is JSON?
I've got the following example code right now:
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class Router extends Silex\Application
{
function __construct() {
parent::__construct();
// routes
$this->match('/{context}', array($this, 'handler'));
// error handler
$this->error(function(\Exception $e, $code) {
return $this->json(array("error" => $e->getMessage()), $code);
});
}
function handler(Request $request, $context) {
// throw new \Exception('test'); // exception- this is caught
$t = new Test(); // error- this is not caught
return 'DONE';
}
}
Symfony\Component\Debug\ErrorHandler::register();
$app = new Router();
$app->run();