Cakephp在自定义Exception.renderer中渲染XML错误

时间:2013-05-28 09:35:12

标签: cakephp cakephp-2.2

根据此处的信息:Using a custom renderer with Exception.renderer to handle application exceptions

我正在创建一个以XML格式呈现的自定义错误渲染器。

下面是app / Lib / Error / AppExceptionRenderer中渲染函数的示例代码:

public function render() {
    if (isset($this->controller->request->params['xml'])) {
        $this->controller->viewClass = "MyXml";
        $error = array(
            'app' => array(
                'error' => 'An unexpected error has occured.'
            )
        );
        $this->controller->set('error', $error);
        $this->controller->set('_serialize', 'error');
    }
}

但是没有任何回复。我在if条件下做了一些回音,显示出来。

那是因为viewClass在AppExceptionRenderer :: render()阶段没有被初始化吗?

也没有错误。
“MyXml”viewClass也可以在普通控制器中完美运行。

1 个答案:

答案 0 :(得分:1)

显然我错过了渲染和发送方法 这是完整的工作示例。

<?php
class AppExceptionRenderer extends ExceptionRenderer {

    public function __construct($exception) {
            parent::__construct($exception);
    }

    public function render() {

        // Handle errors
        if (isset($this->controller->request->params['xml'])) {
            Cakelog::error($this->error->getMessage());
            $this->controller->viewClass = "MyXml";
            $error = array(
                'app' => array(
                    'error' => 'An illegal operation has been detected.'
                )
            );
            $this->controller->set('error', $error);
            $this->controller->set('_serialize', 'error');
            $cakeResponseObject = $this->controller->render();
            $this->controller->response->send($cakeResponseObject);
        } else {
            if ($this->method) {
                call_user_func_array(array($this, $this->method), array($this->error));
            }
        }
    }
}