5
votes

The problem

I'm building a small application with Silex. It's divided between a REST application and a website. (two controllers, same app). The website has installed its own custom error handler, which returns a user friendly html page. The problem is that in the part dedicated REST application, I should somehow handle exceptions to return type [json] and content different from the error handler's custom website.

With Symfony2

This argument can also be applied to Symfony2, I would like also possible solution for it!

A first solution for Silex

Wrap the methods in try-catch block in order to rethrowing the exception to handler.

$app->get('/api/show-list', function() use($app){
    try {
        $show = // db query, etc.
        return $app->json(array('show' => $show), 200);
    } catch (Exception $e) {
        throw new MyException;
    }
});

$app->error(function (MyException $e, $code) {
    // error api
});

The issue is that if an exception is thrown out of my controllor the default error handler will be used. Some tips? And with Symfony?

2
You could create your own exception class that has other variables, one of which you could use to indicate whether to return json or not, then just have one error handler that checks the value and does the appropriate response. - gunnx
And where should I indicate that? - Federkun
Do you have any code for MyException Class that you can add to the question? - gunnx
@gunnx, I mean, where in the flow of my request I should include an hypothetical MyException::isJsonError - Federkun
Did you try actually returning a response from your custom error function? As I believe it will try other handlers until one of them returns something. - gunnx

2 Answers

10
votes

I have been using the following in my Silex RESTful app to return errors in json format:

$app->error(function (\Exception $e, $code) use($app) {
    return $app->json(array("error" => $e->getMessage()),$code);    
});

Not sure if this is the right way, but it works for me.

This is documented on the Silex site: http://silex.sensiolabs.org/doc/usage.html#error-handlers

2
votes

On Symfony2 you can use the ExceptionHandler. On the Exception you have the stack trace, so you can identify where it was thrown.

Also, in Symfony2 you can customize depending on the expected format. It's well explained in it's documentation.

For instance, if you replace the ExceptionController with one of yours, the third parameter shows the expected format:

Reference on where to change the ExceptionController

ExceptionController API