如何捕获pg_connect()函数错误? [英] how to catch pg_connect() function error?

查看:250
本文介绍了如何捕获pg_connect()函数错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

pg_connect()以表格式显示错误。与其以表格式显示错误消息,还需要一条错误消息警报。

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


错误消息

警告:pg_connect()[function.pg-connect]:无法连接到PostgreSQL服务器:致命:在第41行的/home/test/public_html/QueueManager/Modules/Database.php中,用户测试的密码身份验证失败

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()引发异常后。

但不起作用。

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

代码

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();
  }
}

请给我解决方法

推荐答案

pg_connect 不会引发异常,因此您必须将其转换为如下所示的异常。

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

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();
}

请参阅此详细信息

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

这篇关于如何捕获pg_connect()函数错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆