报告级别 0 上的 Cakephp 2 错误

Cakephp 2 errors on reporting level 0

我想在报告级别设置为 0 时显示自定义错误页面,它是 500 错误 而不是 404.在默认视图之外,我似乎根本无法访问错误消息。

我想在正常错误布局之外设置自定义布局。我知道如果我将报告切换到 1 级或 2 级,那么它就可以正常工作。我希望将其设置为 0 而不是 400 错误的生产环境。这可能吗?

$error->getMessage()

Q: I would like to show a custom error page when the reporting level is set to 0 and it is a 500 error

A: 您可以在 [=15] 中编辑默认错误视图 error400.ctp 以及 error500.ctp =]

Q: I would like to set a custom layout outside of the normal error layouts.

A: 如果您想使用另一个(自定义)布局,您可以将文件 CakeErrorController.php/lib/Cake/Controller/ 复制到 /app/Controller/ 并在函数中添加以下行:

function __construct($request = null, $response = null) {
  $this->layout = 'your-layout-name'; // add this line in the function
  // ...
}

并照常在 /app/View/Layouts/ 中添加 custom layout 模板文件,例如your-layout-name.ctp

如果你想在错误 page/layout 中显示来自你的应用程序的数据(例如从数据库生成主菜单)你也可以在你的错误控制器中添加更多自定义代码,例如:

// Error controller in /app/Controller/CakeErrorController.php
class CakeErrorController extends AppController {
  public $uses = array('MenuCategory'); // load relevant table/model
  public function __construct($request = null, $response = null) {
    $this->set('mainmenu', $this->MenuCategory->getMenu()); // or find() or whatever
    // ...
  }
}

Q: How can I keep different error messages in production mode (debug level = 0)?

A 根据 documentation "ErrorHandler by default, displays errors when debug > 0, and logs errors when debug = 0." 原因例如您不应向 public 访问者(在生产模式下)显示 "Missing Component" 之类的错误消息,因为此错误与访问者无关且无用(因此响应 404/500)。这些类型的错误仅与开发相关,应在生产模式上线前修复。

如果您想要更改此行为,您必须设置自己的错误处理,如有必要,已在 book. Please also have a look at the explanation directly in the CakePHP code. You can also create your own exeptions 中进行说明。

如果您在 using/creating 您自己的错误处理程序中遇到问题,请在 Whosebug 上开始一个新问题并提供更多详细信息:您创建了哪些文件(例如 您的错误处理程序 and/or 例外),你的代码是什么样子的,你尝试过什么来解决问题......请给出一个明确的例子来说明你想要实现什么(例如在下面的第一版评论中我的回答是你在谈论特殊的 500 错误 - 是什么触发了这些错误,你想响应什么而不是 500 或者你到底想改变什么...)?

另一种解决方案在某些情况下也可能是这样的:

// In your controller
public function moderator_view($id = null) {
  // Your error check, in this example the user role
  if ( $this->Auth->user('role') != 'moderator' ) {
    // Custom error message
    $this->Flash->custom('You are not a moderator.');
    // Redirect to your your special error page
    // In this example got to previous page
    return $this->redirect(
      $this->referer(
        // or go to a default page if no referrer is given
        array('controller' => 'articles', 'action' => 'index', 'moderator' => false)
        )
      );
  }
  // else show moderator content...
}

另请查看 many other questions 在 CakePHP 中自定义错误页面 ;-)