I am trying to build an REST web service that returns JSON for all calls. Normally this is pretty straightforward, I just do like this:
return new Response(json_encode($return_object));
My question is, how should I intercept exceptions in a global way? I want to do this, because if an exception happens anywhere in my application, I'd still like to return a JSON message to the client saying basically "Yo dawg, I heard you like exceptions". My thinking is that returning JSON in both success and failure cases will simplify the work that any client needs to do to implement my API.
So far, the only thing I can think of is to write every controller action like this:
public function generateMemeAction($arg1, $arg2) {
$return_object = array();
try {
// stuff to 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 is all great and wonderful, but that try-catch block will be the same for every action in my app, and I will feel silly every time I have to edit around a bunch of copy pasta. Pro tips?
REST app have different type of errors. E.g. you can have logical errors or input errors (not all parameters were send). Different types of errors should be handling using diffent ways. The best way for that case is manual handling of these errors.
You can add to your Controller special error method (and put it e.g. into parent class) which will return error code + error text.
But if you want to use automatic handling you can use Exception listener:
Here is a sample:
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
$response = new Response();
// setup the Response object based on the caught exception
$event->setResponse($response);
// you can alternatively set a new Exception
// $exception = new \Exception('Some special exception');
// $event->setException($exception);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With