简体   繁体   English

如何阻止php脚本将错误附加到浏览器?

[英]How to stop php script from appending error to the browser?

I am new to PHP. 我是PHP新手。 Please excuse if the question is pretty obvious. 如果问题很明显,请原谅。 This is my code - 这是我的代码-

$giftAssocs2 = UserGiftAssoc::getUserGiftAssocs($userid);
$newmailer = new MAIL_CLASS;
$newmailer->sendMail($giftAssocs2 , "Hello", 'xxxx@gmail.com', $mailID);
return $giftAssocs2;

First line is able to fetch the details properly. 第一行能够正确获取详细信息。 However mail does not send due to some smtp host related errors. 但是由于某些smtp主机相关的错误,邮件无法发送。 Coming from the java background , I expect to see some error in the console since I have not handled the exception. 来自Java背景,由于未处理异常,我希望在控制台中看到一些错误。 However my result is like this - 但是我的结果是这样的-

SMTP -> ERROR: Failed to connect to server: (0) SMTP Error: Could not connect to SMTP host. SMTP->错误:无法连接到服务器:(0)SMTP错误:无法连接到SMTP主机。 {"status":"true","msg":"success","details":[{XXX}]} {“状态”:“真”,“消息”:“成功”,“详细信息”:[{XXX}]}

So I get the error appended by the actual result. 所以我得到了实际结果附加的错误。 I was wondering how is this possible and how to avoid this ? 我想知道这怎么可能以及如何避免呢?

It probably makes sense, if you're expecting it to sometimes error, to use a try/catch . 如果您期望有时会出错,则使用try / catch可能是有道理的。

If that doesn't work for you, you can use the dreaded @ to make sure the error doesn't get shown: 如果那对您不起作用,则可以使用可怕的@来确保不会显示错误:

PHP supports one error control operator: the at sign (@). PHP支持一种错误控制运算符:at符号(@)。 When prepended to an expression in PHP, any error messages that might be generated by that expression will be ignored. 当在PHP表达式中添加前缀时,该表达式可能生成的任何错误消息都将被忽略。

So for example: 因此,例如:

$sent = @$newmailer->sendMail($giftAssocs2 , "Hello", 'xxxx@gmail.com', $mailID);
if($sent) {
    //...

The reason I say it's "dreaded" is that you're basically saying "I don't really care if this works", and usually, instead of using the @ , you'd use a try/catch. 我之所以说它“令人恐惧”,是因为您基本上是在说“我真的不在乎这是否可行”,通常,您不使用@而是使用try / catch。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM