使用REST应用程序的不同处理程序捕获异常 [英] Capture exceptions with a different handler for applications REST

查看:131
本文介绍了使用REST应用程序的不同处理程序捕获异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Silex 构建一个小应用程序。它分为REST应用程序和网站之间。 (两个控制器,同一个应用程序)。
该网站已安装其自己的自定义错误处理程序,返回用户友好的html页面。问题在于,在部分专用的REST应用程序中,我应该以某种方式处理异常以返回类型[json]和与错误处理程序的自定义网站不同的内容。

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.

这个参数也可以应用于Symfony2,我也想为它提供解决方案!

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

在try-catch块中包装方法,以将异常重新抛出到处理程序中。

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
});

问题是如果从我的控制器中抛出异常,将使用默认错误处理程序。一些技巧?
和Symfony?

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?

推荐答案

我在Silex RESTful应用程序中使用以下内容,以json格式返回错误:$($)
$ b

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.

这是在Silex网站上记录的:
http: /silex.sensiolabs.org/doc/usage.html#error-handlers

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

这篇关于使用REST应用程序的不同处理程序捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆