如果无法访问Web上的某些内容(api,数据库),我将如何停止执行脚本的其余部分并将错误记录在日志文件中?那么,让访问者不会看到确切的原因,而是他们会看到我的自定义信息(比如说'发生了一件坏事')。我需要采取哪些步骤来安排事情?PHP:如何优雅地管理错误?
回答
,并让游客不会看到 确切原因,而是他们会 看到我的自定义消息
我建议你去通过大卫·沃尔什这个优秀的文章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.
我通常喜欢用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
:那是,在我看来,中处理错误的最糟糕的方式之一。
我还要配置我的服务器/应用程序,以便:
- 错误信息不被输出中显示,设置
display_errors
到Off
。 - 使用
log_errors
和error_log
将错误记录到文件中。
如果在catch语句后面有代码会怎么样?你应该简单地用'die()'完成每个'catch'吗? – Blauhirn 2016-07-27 09:56:06
- 1. 如何优雅地处理ViewState错误?
- 2. angular $ http优雅地处理错误
- 3. Go - 优雅地处理多个错误?
- 4. 如何在Kohana/PHP中优雅地管理数据库事务
- 5. 优雅地转义错误
- 6. Express 4/Node JS - 优雅地管理uncaughtException
- 7. 如何在PocketSphinx for Android中优雅地处理错误?
- 8. 我应该如何优雅地处理错误的AppDomains?
- 9. amCharts:如何优雅地管理dataLoader中的数据缺失
- 10. Python - 如何优雅地处理TypeError?
- 11. 如何优雅地处理DefaultControlFactory的CreateController
- 12. 如何优雅地处理Jackson InvalidFormatException?
- 13. 如何优雅地处理maxRequestLength异常?
- 14. 如何优雅地处理零例外?
- 15. Cascading DropDown优雅地捕捉错误
- 16. 优雅地处理socket.close()
- 17. 如何优雅地处理php内容包含?
- 18. 如何优雅地死去?
- 19. 优雅地处理媒体播放器错误
- 20. PHP更优雅的方式来处理mysqli的错误
- 21. 技术PHP/SQL错误的优雅处理
- 22. 管理PHP错误
- 23. 错误地停止ASP.NET MVC 2 REST svc优雅地出错
- 24. 优雅地处理“MySQL已经消失”
- 25. 优雅地处理TypeMirror和Class
- 26. 优雅地处理AsyncTask中的IOException?
- 27. 优雅处理大的MySQL行由PHP
- 28. Php用户代理优雅的退化
- 29. 如何优雅地登录Doctrine2实体
- 30. 如何优雅地关闭Rserve?
异常更好 – 2010-03-02 13:54:49
@FractalizeR:我也发布了链接。谢谢 – Sarfraz 2010-03-02 13:55:46