rest - How to catch all exceptions that could arise in Symfony2 controller action? -


i trying build rest web service returns json calls. pretty straightforward, this:

return new response(json_encode($return_object)); 

my question is, how should intercept exceptions in global way? want this, because if exception happens anywhere in application, i'd still return json message client saying "yo dawg, heard exceptions". thinking returning json in both success , failure cases simplify work client needs implement api.

so far, thing can think of write every controller action this:

public function generatememeaction($arg1, $arg2) { $return_object = array(); try { // stuff generate meme here $return_object['status'] = "great success!"; } catch (exception $e) { // epic fail $return_object['status'] = "unluckybrianexception"; } return new response(json_encode($return_object)); } 

which great , wonderful, try-catch block same every action in app, , feel silly every time have edit around bunch of copy pasta. pro tips?

rest app have different type of errors. e.g. can have logical errors or input errors (not parameters send). different types of errors should handling using diffent ways. best way case manual handling of these errors.

you can add controller special error method (and put e.g. parent class) return error code + error text.

but if want use automatic handling can use exception listener:

here sample:

use symfony\component\httpkernel\event\getresponseforexceptionevent; use symfony\component\httpfoundation\response; public function onkernelexception(getresponseforexceptionevent $event) { $exception = $event->getexception(); $response = new response(); // setup response object based on caught exception $event->setresponse($response); // can alternatively set new exception // $exception = new \exception('some special exception'); // $event->setexception($exception); } 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -