【问题标题】:In Kohana, can you trigger a 404 error?在 Kohana 中,可以触发 404 错误吗?
【发布时间】:2010-10-24 01:40:44
【问题描述】:

我有一个名为articles 的控制器,它创建从数据库中获取相关数据的文章模型。

如果我调用的方法返回false,我想触发404错误。这是我目前所拥有的。

 $articleName =  $this->uri->segment('articles');

 $article = new Articles_Model();

 $data = $article->getArticleUsingSlug($articleName);

 if (!$data) {
    Kohana::show_404; // This doesn't work.
 }

我刚刚添加了我自己的自定义钩子,它将用户重定向到由 Kohana 触发的实际 404 (/articles/page-not-found/),但是有没有一种方法可以调用其内部 404 方法来让 Kohana处理我的控制器并使用我的新钩子?

【问题讨论】:

  • 不能只用php头方法然后die()吗?
  • @Nael El Shawwa 当有更好的选择时不会。

标签: php kohana http-status-code-404


【解决方案1】:

这对我有用:

Event::run('system.404');

您使用的是什么版本的 Kohana?

【讨论】:

  • 还要注意 if $config['display_errors'] = TRUE;您将看到一个堆栈跟踪以及您的 404 页面。如果您只想显示 404 页面,请设置 display_errors = FALSE
【解决方案2】:

Kohana / 常规 / 错误处理 / Kohana_404_Exception

/**
 * @param  string  URL of page
 * @param  string  custom error template
 */
throw new Kohana_404_Exception([string $page [, string $template]]);

【讨论】:

  • 感谢您的回答 - 迟到总比没有好! +1
  • 其他人将来可能会偶然发现这个问题:)
  • 作为更新,在 Kohana 3.3 中它是 throw new Kohana_HTTP_Exception_404()
【解决方案3】:

Kohana Docs 告诉你怎么做:

throw HTTP_Exception::factory(404, 'File not found!');

【讨论】:

    猜你喜欢
    • 2011-04-08
    • 2015-03-02
    • 1970-01-01
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    相关资源
    最近更新 更多