php教程

Exception::getCode

(PHP 5, PHP 7)

Exception::getCode获取异常代码

说明

final public Exception::getCode ( void ) : int

返回异常代码。

参数

此函数没有参数。

返回值

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

范例

Example #1 Exception::getCode()示例

<?php
try {
    throw new 
Exception("Some error message"30);
} catch(
Exception $e) {
    echo 
"The exception code is: " $e->getCode();
}
?>

以上例程的输出类似于:

The exception code is: 30

参见

  • Throwable::getCode()

User Contributed Notes

ahmad dot mayahi at gmail dot com 06-Mar-2017 09:45
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:

<?php
//I have a mysql table called hosts with one unique key named host_name.
 
try {
    
$hosts = new Hosts(["host_name" => "www.example.com");
    
$hosts->save();
 } catch (\
PDOException $e) {
      if (
$e->getCode() === 23000) {
         
//Do nothing
    
}
}
?>

Here I'm saving the host name, and I don't care if it's already exists.
talksonweb at gmail dot com 28-Jun-2013 03:23
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.
ricky at rocker dot com 19-Feb-2013 10:53
when raising an Exception with no error code explicitly defined, getCode() returns the integer 0

<?php
try {
  throw new
Exception("no code!!");
} catch (
Exception $e) {
  print(
"Code='" . $e->getCode() . "'");
}
?>

outputs

Code='0'

CopyRight © 2008-2022 verySource.Com All Rights reserved. 京ICP备17048824号-1 京公网安备:11010502034788