2010-03-02 48 views
2

如果无法访问Web上的某些内容(api,数据库),我将如何停止执行脚本的其余部分并将错误记录在日志文件中?那么,让访问者不会看到确切的原因,而是他们会看到我的自定义信息(比如说'发生了一件坏事')。我需要采取哪些步骤来安排事情?PHP:如何优雅地管理错误?

回答

2

,并让游客不会看到 确切原因,而是他们会 看到我的自定义消息

我建议你去通过大卫·沃尔什这个优秀的文章custom error handling in PHP

您可以使用set_error_handler()功能。

我怎么会停止执行的 其余的脚本和记录错误的 日志文件?

有一个PHP的默认函数来记录错误;从PHP.net error_log

实施例:

<?php 
// Send notification through the server log if we can not 
// connect to the database. 
if (!Ora_Logon($username, $password)) { 
    error_log("Oracle database not available!", 0); 
    exit; //exit 
} 

// Notify administrator by email if we run out of FOO 
if (!($foo = allocate_new_foo())) { 
    error_log("Big trouble, we're all out of FOOs!", 1, 
       "[email protected]"); 
} 

// another way to call error_log(): 
error_log("You messed up!", 3, "/var/tmp/my-errors.log"); 
?> 

更多资源:

This is also good article covering most of it related to error handling.

+0

异常更好 – 2010-03-02 13:54:49

+0

@FractalizeR:我也发布了链接。谢谢 – Sarfraz 2010-03-02 13:55:46

11

我通常喜欢用Exceptions,在那种情况:它让我有所有错误处理代码在一个地方。


举例来说,我会使用的东西有点像这样:

try { 
    // Some code 

    // Some code that throws an exception 

    // Some other code -- will not be executed when there's been an Exception 

} catch (Exception $e) { 
    // Log the technical error to file/database 

    // Display a nice error message 
} 

就这样,所有的错误处理代码是在catch块 - 而不是scatterred accros我的整个应用程序。


但是请注意,许多PHP函数不抛出异常,只提出一个警告或错误......

对于这些,你可以使用set_error_handler来定义自己的错误处理 - 这可能会抛出异常;-)
例如,请参阅manual page of ErrorException上的示例。

虽然这将工作真实细腻了很多错误/警告,你要注意,它不会为Parse Error也不Fatal Error工作:前实际执行 PHP代码

  • 第一种是实际募集
  • 第二种是...好...致命。


而且我绝不会放在我的代码中任何die也不exit:那是,在我看来,中处理错误的最糟糕的方式之一。

我还要配置我的服务器/应用程序,以便:

+0

如果在catch语句后面有代码会怎么样?你应该简单地用'die()'完成每个'catch'吗? – Blauhirn 2016-07-27 09:56:06