百科狗-知识改变命运!

PDOException异常类 - PDO驱动

百变鹏仔2年前 (2023-11-21)阅读数 30#技术干货
文章标签异常

PDOException异常类

(PHP 5 >= 5.1.0, PHP 7)

代表一个由 PDO 产生的错误。在自己的代码不应抛出一个 PDOException 异常

PDOException extends RuntimeException
{
	/* 属性 */
	public array $errorInfo ;
	protected string $message ;
	protected string $code ;
	/* 继承的方法 */
	final public Exception::getMessage ( void ) : string
	final public Exception::getPrevious ( void ) : Throwable
	final public Exception::getCode ( void ) : int
	final public Exception::getFile ( void ) : string
	final public Exception::getLine ( void ) : int
	final public Exception::getTrace ( void ) : array
	final public Exception::getTraceAsString ( void ) : string
	public Exception::__toString ( void ) : string
	final private Exception::__clone ( void ) : void
}

属性

  • errorInfo:相当于PDO::errorInfo() 或 PDOStatement::errorInfo()
  • message:文本错误信息。用 Exception::getMessage() 来访问。
  • code:SQLSTATE 错误码。用Exception::getCode() 来访问。

Exception::getMessage

(PHP 5, PHP 7)

获取异常消息内容

说明

finalpublicException::getMessage(void) : string

返回异常消息内容。

参数

此函数没有参数。

返回值

返回字符串类型的异常消息内容。

范例

Exception::getMessage()示例


以上例程的输出类似于:

Some error message

参见

  • Throwable::getMessage()

Exception::getCode

(PHP 5, PHP 7)

获取异常代码

说明

finalpublicException::getCode(void) : int

返回异常代码。

参数

此函数没有参数。

返回值

Exception 返回整型(integer)的异常代码,但在其他类中可能返回其他类型(比如在 PDOException 中返回 string)。

PDOException异常类 - PDO驱动

范例

Exception::getCode()示例


以上例程的输出类似于:

The exception code is: 30

参见

  • Throwable::getCode()
The exception code can be used to categorize your errors. If you're wondering what the exception code can be used for, read on below. 
Let's say each time your application isn't able to connect to the database, you can save the error message under the error/exception code 214. At the end of the month, you can do a quick search on the error number '214' and find out how many times this error occurred. This makes life easier. Also, the error/exception message will give you details into what happened. 
The point is to use both the exception message and code. It's helpful in the long run.
Note: I added this note, because I was confused earlier as to the purpose of the exception code and it's use.
One of the most useful tricks of getCode is handling duplication entries when trying to add a duplicate row into the database.
Sometimes we don't need to show any errors regarding this duplication.
The following snippet is taken from one of my projects:

Here I'm saving the host name, and I don't care if it's already exists.
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0 

内容声明:本文中引用的各种信息及资料(包括但不限于文字、数据、图表及超链接等)均来源于该信息及资料的相关主体(包括但不限于公司、媒体、协会等机构)的官方网站或公开发表的信息。部分内容参考包括:(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供参考使用,不准确地方联系删除处理!本站为非盈利性质站点,本着为中国教育事业出一份力,发布内容不收取任何费用也不接任何广告!)
{if $zbp->Config('yd1125')->foot}