输出自定义错误消息而不是默认的PHP错误消息

时间:2012-12-21 02:48:19

标签: php

我在我的程序的一部分中使用PHP复制功能,其中函数的参数取决于用户输入。我试图避免默认的PHP错误消息,如果它们包含该功能无法使用的路径,并输出如下所示的自定义消息。我是处理错误/异常的新手。我仍然收到PHP默认错误消息而不是自定义'路径不正确!'使用以下方法。

我尝试了什么:

try{
    copy($webImagePath, $destinationPath);
 }
 catch(Exception $e){
    echo 'Path was incorrect!';
 }

2 个答案:

答案 0 :(得分:0)

考虑set_error_handlerhttp://php.net/manual/en/function.set-error-handler.php

示例:

set_error_handler("someFunction");

function someFunction($errno, $errstr) {
    output details and information
}

答案 1 :(得分:0)

您应该使用希望显示的自定义消息抛出异常。 您可以通过在前面添加“@”符号来抑制单个语句的默认PHP错误消息。或者您可以更改每页的error_reporting级别(有关详细信息,请查看此链接:http://php.net/manual/en/function.error-reporting.php

另请查看以下代码段

$file='example.txt';          //replace the file name with your URL
$newfile = 'example.txt.bak';
try{
  $ret=@copy($file, $newfile);
  if (!$ret){
    throw new Exception("File path doesn't exist..");
  }
}
catch(Exception $e){
echo $e->getMessage();
}
相关问题