-->

Capture exceptions with a different handler for ap

2019-04-10 04:02发布

问题:

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?

回答1:

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:

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