php - How can I catch errors and exceptions in Symfony2/Silex? -
I would like to grab both errors and exceptions to wrap them in a custom JSON response in my Syllax app that will always be I returned three basic methods to customers:
$ app-> Error () Symfony \ Component \ Debug \ ErrorHandler :: register (); Symfony \ Component \ Debug \ ExceptionHandler :: Register (); I am able to capture controller exceptions using error () , but I have failed with php errors - they always end in xdebug . I have also failed 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:
Use Silex \ Application; Use Symfony \ Component \ HttpFoundation \ Request; Use Symfony \ Component \ HttpFoundation \ Response; Class router silks \ extension extends {function __construct () {parent :: __ construct (); // Route $ this- & gt; Match ('/ {reference}', array ($ this, 'handler')); // error handler $ - this-> error (function (\ exception $ e, $ code) {return $ this-> json (array ("error" =>> $ e-> getMessage ()) , $ Code);}); } Function handler (request $ request, $ reference) {// throw new exception ('test'); // Exception - This $ t = new test () has been caught; // error - this 'refund' has not been caught back; }} Symfony \ Component \ Debug \ ErrorHandler :: register (); $ App = new router (); $ App- & gt; Run ();
You can catch your errors like exceptions
example
Use symphony \ component \ debug \ expansion handler; Use Symfony \ Component \ Debug \ ErrorHandler; /// Bla bla bla Hold some code / all errors and convert them into exceptions ErrorHandler :: register (); Try {// error trigger_error here for example ('Oh my God, I am on fire'); } Hold (\ Exception $ E) {// You can make this $ handler = new exception handler for debugging; $ Handler- & gt; Handle ($ E); / * * ExceptionHendler Class Comment * This is useful in default dpb mode, which is to replace the default PHP / XDebug * output with something special and more useful. * So I suggest to change Jason's reaction * and replace this code $ handler = new exception handler (); * $ Handler- & gt; Handle ($ E); * / New JasonResons Returns (array ('condition' = & gt; 'error', 'message' =>> $ e-> messages received ()); } You can do the next thing with Syllax
ErrorHandler :: register (); // An error handler $ app- & gt; Use the error (function (\ exception $ e, $ code) ($ app) {// Return your Jason response back to $ error = array ('message' = & gt; $ e- & Gt; received message ()) ; Return $ app-> Jason ($ error, 200);});
Comments
Post a Comment