Capture exceptions with a different handler for applications REST

陌路散爱 提交于 2020-01-01 14:10:34

问题


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



来源:https://stackoverflow.com/questions/14872816/capture-exceptions-with-a-different-handler-for-applications-rest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!