php 如何捕获 pg_connect() 函数错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4253136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:24:43  来源:igfitidea点击:

how to catch pg_connect() function error?

phppostgresql

提问by ungalnanban

pg_connect() is showing the error in table format.Instead of showing error message as table format need a error message alert.

pg_connect() 以表格格式显示错误。而不是显示错误消息,因为表格格式需要错误消息警报。

Error Message
Warning: pg_connect() [function.pg-connect]: Unable to connect to PostgreSQL server: FATAL: password authentication failed for user "test" in /home/test/public_html/QueueManager/Modules/Database.php on line 41

错误消息
警告:pg_connect() [function.pg-connect]:无法连接到 PostgreSQL 服务器:致命:第 41 行 /home/test/public_html/QueueManager/Modules/Database.php 中用户“test”的密码验证失败

After if showing error as table format.
After executing pg_connect() throwed exception.
But is is not working.

之后如果显示错误为表格格式。
执行 pg_connect() 后抛出异常。
但是是行不通的。

Code

代码

function connect()
{
  $HOST = $GLOBALS[Database_Conn][Db_Host];     # Host name 
  $USER = $GLOBALS[Database_Conn][Db_User];     # database user name 
  $DBNAME = $GLOBALS[Database_Conn][Db_Name];   # name of the database
  $PASSWORD = $GLOBALS[Database_Conn][Db_Pass]; # password the database user.

  try 
  {
    $conn = pg_connect("host=$HOST dbname=$DBNAME user=$USER ".
                       "password=$PASSWORD sslmode=disable");
    if(!$conn)
    {
      throw new Exception("Database Connection Error");
    }
    return $conn;
  }
  catch (Exception $e) 
  {
    print <<<_HTML_
    <script> alert('Caught exception'); 
    </script> _HTML_;
    die();
  }
}

Please give me the solution

请给我解决方案

回答by user2548654

pg_connectdoes not throw exception, so you have to translate to exception like below.

pg_connect不会抛出异常,因此您必须转换为如下异常。

function exception_error_handler($errno, $errstr, $errfile, $errline ) {
    throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
}
set_error_handler("exception_error_handler");

try {
    $conn=@pg_connect("host=dbhost user=dbuser dbname=db password=dbpass");
} Catch (Exception $e) {
    Echo $e->getMessage();
}

Please refer this more detail

请参阅此更多详细信息

http://php.net/manual/en/language.exceptions.php

http://php.net/manual/en/language.exceptions.php

回答by intgr

To hide the error text generated by PHP, add @ in front of the function call, e.g.:

要隐藏 PHP 生成的错误文本,请在函数调用前添加 @,例如:

$conn = @pg_connect("host=$HOST dbname=$DBNAME user=$USER ".
                   "password=$PASSWORD sslmode=disable");

More details here

更多细节在这里