rest - ExceptionStrategy 不适用于 JsonStrategy

标签 rest zend-framework2

我遇到了此处报告的问题 ( http://framework.zend.com/issues/browse/ZF2-379?page=com.atlassian.streams.streams-jira-plugin:activity-stream-issue-tab#issue-tabs )。有一个解决方案,但我不知道在哪里实现。有人可以帮忙吗?

问候,

最佳答案

这是 JsonExceptionStrategy 的代码 - 将其放在某个地方,例如模块中。

namespace YourNamespace;

use Zend\EventManager\EventManagerInterface;
use Zend\Mvc\Application;
use Zend\Mvc\View\Http\ExceptionStrategy;
use Zend\Mvc\MvcEvent;
use Zend\View\Model\JsonModel;

/**
 *
 * @since   1.0
 * @author  Tim Roediger <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cbb8bebbaeb9afbcaeaea9a2ae8baca6aaa2a7e5a8a4a6" rel="noreferrer noopener nofollow">[email protected]</a>>
 */
class JsonExceptionStrategy extends ExceptionStrategy
{

    /**
     * Attach the aggregate to the specified event manager
     *
     * @param  EventManagerInterface $events
     * @return void
     */
    public function attach(EventManagerInterface $events)
    {
        $this->listeners[] = $events->attach(MvcEvent::EVENT_DISPATCH_ERROR, array($this, 'prepareExceptionViewModel'), 100);
    }

    /**
     * Create an exception json view model, and set the HTTP status code
     *
     * @todo   dispatch.error does not halt dispatch unless a response is
     *         returned. As such, we likely need to trigger rendering as a low
     *         priority dispatch.error event (or goto a render event) to ensure
     *         rendering occurs, and that munging of view models occurs when
     *         expected.
     * @param  MvcEvent $e
     * @return void
     */
    public function prepareExceptionViewModel(MvcEvent $e)
    {
        // Do nothing if no error in the event
        $error = $e->getError();
        if (empty($error)) {
            return;
        }

        // Do nothing if the result is a response object
        $result = $e->getResult();
        if ($result instanceof Response) {
            return;
        }

        switch ($error) {
            case Application::ERROR_CONTROLLER_NOT_FOUND:
            case Application::ERROR_CONTROLLER_INVALID:
            case Application::ERROR_ROUTER_NO_MATCH:
                // Specifically not handling these
                return;

            case Application::ERROR_EXCEPTION:
            default:
                $exception = $e->getParam('exception');
                $modelData = array(
                    'message' => $exception->getMessage(),
                    'type' => get_class($exception)
                );

                if ($this->displayExceptions()){
                    $modelData['exception'] = $exception;
                }
                $e->setResult(new JsonModel($modelData));
                $e->setError(false);

                $response = $e->getResponse();
                if (!$response) {
                    $response = new HttpResponse();
                    $e->setResponse($response);
                }
                $response->setStatusCode(500);
                break;
        }
    }
}

然后在 Module.php 中添加以下内容:

/**
 *
 * @param \Zend\EventManager\Event $event
 */
public function onBootstrap(MvcEvent $event)
{

    $application = $event->getTarget();
    $serviceManager = $application->getServiceManager();
    $config = $serviceManager->get('Config');

    // Config json enabled exceptionStrategy
    $exceptionStrategy = new JsonExceptionStrategy();

    $displayExceptions = false;

    if (isset($config['view_manager']['display_exceptions'])) {
        $displayExceptions = $config['view_manager']['display_exceptions'];
    }

    $exceptionStrategy->setDisplayExceptions($displayExceptions);
    $exceptionStrategy->attach($application->getEventManager());
}

你可以走了!

关于rest - ExceptionStrategy 不适用于 JsonStrategy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14625360/

相关文章:

java - 包含路径的 URI 模板变量?

node.js - 通过 Angular App 和 NodeJS 发送 GET/POST 请求到 express 服务器时如何修复 404 Not Found

java - 使用 Jersey 进行基于用户的访问的 REST 设计

.htaccess - Zend Framework 2 中从 .htaccess 到 web.config 的 URL 重写

symfony - Zend Framework 2 和 Symfony 2 的主要区别

php - Zend Framework 2 模型架构

java - 我可以使用 pico 容器共享同一类的两个对象吗?

mysql - ZF2AuthAcl 模块无法开箱即用

php - ZF2,添加多个表

java - 如何使用 JAXB 使用 Jersey 1.6 生成 JSON 输出