2

希望你能帮我解决这个奇怪的问题:我试图从控制器中重定向,但 Kohana 不断抛出一个我无法弄清楚原因的异常:

Cadastro.php 中的代码:

try{
     $this->redirect('/dados', 302);
} catch (Exception $e) {
                $this->response->body(Json_View::factory(array("line ".$e->getLine()." of file ".$e->getFile().":".$e->getMessage()." - trace as string: ".$e->getTraceAsString())));
}            }

上面代码中异常返回的堆栈跟踪消息是:

#0 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\HTTP.php(33): Kohana_HTTP_Exception::factory(302)
#1 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\Controller.php(127): Kohana_HTTP::redirect('\/dados', 302)
#2 C:\\xampp\\htdocs\\grademagica\\modules\\grademagica\\classes\\Controller\\Cadastro.php(123): Kohana_Controller::redirect('\/dados', 302)
#3 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\Controller.php(84): Controller_Cadastro->action_signin()
#4 [internal function]: Kohana_Controller->execute()
#5 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\Request\\Client\\Internal.php(97): ReflectionMethod->invoke(Object(Controller_Cadastro))
#6 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\Request\\Client.php(114): Kohana_Request_Client_Internal->execute_request(Object(Request), Object(Response))
#7 C:\\xampp\\htdocs\\grademagica\\system\\classes\\Kohana\\Request.php(990): Kohana_Request_Client->execute(Object(Request))
#8 C:\\xampp\\htdocs\\grademagica\\index.php(123): Kohana_Request->execute()
#9 {main}

Cadastro.php 中的第 123 行是“$this->redirect('/dados', 302);”,如上所述。有谁可以帮助我展示我做错了什么?我正在遵循文档的确切说明

谢谢

4

1 回答 1

5

让我们看看发生了什么。

你调用$this->redirect('/dados', 302);,让我们看一下它的源代码:

public static function redirect($uri = '', $code = 302)
{
    return HTTP::redirect($uri, $code);
}

好的,我们知道$this->redirect('/dados')就足够了,接下来让我们看看 HTTP::redirect():

public static function redirect($uri = '', $code = 302)
{
    $e = HTTP_Exception::factory($code);

    if ( ! $e instanceof HTTP_Exception_Redirect)
        throw new Kohana_Exception('Invalid redirect code \':code\'', array(
            ':code' => $code
        ));

    throw $e->location($uri);
}

它将创建一个异常(HTTP_Exception_$code)然后抛出它。

异常应该冒泡到Request_Client_Internal::execute_request(),下面的 catch 块应该处理它:

catch (HTTP_Exception $e)
{
    // Get the response via the Exception
    $response = $e->get_response();
}

但是,由于您捕获了异常,因此它不会冒泡。这是修复它的一种方法。

try{
     $this->redirect('/dados', 302);
} catch (HTTP_Exception_Redirect $e) {
    throw $e;
} catch (Exception $e) {
                $this->response->body(Json_View::factory(array("line ".$e->getLine()." of file ".$e->getFile().":".$e->getMessage()." - trace as string: ".$e->getTraceAsString())));
}
于 2013-10-11T20:36:18.503 回答