适当使用die()?

时间:2010-06-14 05:42:40

标签: php exception-handling error-handling die

注意:我正在使用输出缓冲。它只包含在head()和foot()函数中。

我使用以下模板在当前的PHP项目中创建页面:

<?php
include 'bootstrap.php';
head();
?>

<!-- Page content here -->

<?php
foot();
?>

以下示例是否适合使用die()?另外,如果有的话,这会给我带来什么样的问题?

<?php
include 'bootstrap.php';
head();

try
{
    //Simulate throwing an exception from some class
    throw new Exception('Something went wrong!');
}
catch(Exception $e)
{
    ?>
    <p>Please fix the following error:</p>
    <p><?php echo $e->getMessage(); ?></p>
    <?php
    foot();
    die();
}

//If no exception is thrown above, continue script
doSomething();
doSomeOtherThing();

foot();
?>

基本上,我有一个包含多个任务的脚本,我正在尝试设置一种优雅的方式来通知用户输入错误,同时防止脚本的剩余部分执行。

谢谢!

3 个答案:

答案 0 :(得分:4)

我会这样做:

head();
try {
    somethingPossiblyWithError();
    somethingElse();
} catch (Exception $e) {
    handleError();
}
foot();

不需要死亡。如果somethingPossiblyWithError中出现错误,则会跳过somethingElsefoot将在两种情况下执行。

更新:我赞成了Shrapnel上校的答案,因为我猜你没有想到这一点,这是一个有价值的知识。在PHP中,您可以通过output buffering获得等效功能,而无需显式传递值,但它不是很漂亮 - 但是,如果您调用的函数将打印事物并且不将它们作为值返回,那么它有效了解它是有用的。

答案 1 :(得分:3)

整个页面结构错误 虽然这是最普遍的新手错误。

在准备好所有数据之前,不应该输出任何东西 您的脚本可能会发送一些HTTP标头,可能会设置一些变量以供标头()或其他任何内容使用。

因此,模板的使用是必要的 您必须将脚本分为两部分 - 获取数据部分和显示数据部分 因此,您必须将header()函数移动得更低 根据Amadan的答案,它可能是

<?php
include 'bootstrap.php';
try {
  getData();
} catch (Exception $e) {
    handleError();
}
head();
body();
foot();
?>

handleError()函数可以设置适当的HTTP错误代码(404或500)并用错误消息文本替换正文模板。

答案 2 :(得分:1)

出于多种原因,不推荐您的方法。你应该:

  • 将演示文稿和逻辑分开(看看MVC模式)
  • 避免程序代码,编写面向对象的PHP
  • 单独的用户和管理员体验(轻轻处理错误)

示例,上面实现:

<? $page->debug = true; ?>
<?= $page->getHead(); ?>
<?= $page->getBody(); ?>
<?= $page->getFoot(); ?>

class page {

   public debug;

   public function getBody() {
       try {
          //
       } catch (Exception $e) {
          $this->_errorhandler('message');
       }
   }

   protected function _errorhandler($message) {
        if ($this->debug) {
              // display error message
          } else {
             // display nothing, log the error
             // or throw concrete exception
             // or redirect
          }
   }
 ...
}

这也不推荐(每个任务都需要许多单独的类),但你明白了这一点:分离,而不是混合一切。

相关问题