Home> php教程> php手册> body text

Catch and handle PHP exceptions

WBOY
Release: 2016-08-10 08:49:02
Original
1223 people have browsed it

Catch and handle PHP exceptions ~

The system comes with exception handling header("Content-type:text/html;charset=utf-8");
try
{
//Exception thrown when business processing error occurs.
$age = 130;
If ($age > 120) {
throw new Exception('Age cannot be greater than 120 years old.', 1001);
}
} catch (Exception $e) {
$err = [
‘code’ => $e->getCode(),
‘msg’ => $e->getMessage(),
'file' => $e->getFile(),
'line' => $e->getLine()
];
Echo json_encode($err);
}

Output: {"code":1001,"msg":"u5e74u9f84u4e0du80fdu5927u4e8e120u5c81u3002","file":"/data/mi/demo.php","line":11}
Custom exception handling header("Content-type:text/html;charset=utf-8");
class proException extends Exception
{
//Customize the method according to business needs
/**
* Get error message
* @param int $type type 1=json 2=array
* * @return array
*/
Public function getErrorInfo($type = 2)
{
$err = [
‘code’ => $this->getCode(),
'Msg' = & gt; $ this- & gt; getMessage (),
‘line’ => $this->getLine()
];
If ($type == 1) {
return json_encode($err);
}
return }
}

try
{
//Exception thrown when business processing error occurs.
$age = 130;
If ($age > 120) {
throw new proException('Age cannot be greater than 120 years old.', 1001);
}
} catch (proException $e) {
$info = $e->getErrorInfo();
var_dump($info);
}

Output: array(4) { ["code"]=> int(1001) ["msg"]=> string(27) "Age cannot be greater than 120 years old." ["file"]=> string(17 ) "/data/mi/demo.php" ["line"]=> int(53) }

Catch multiple exceptions
header("Content-type:text/html;charset=utf-8");class proException extends Exception
{
//Customize error methods according to business needs

/**
* Get error message
* @param int $type type 1=json 2=array
* * @return array
*/
Public function getErrorInfo($type = 2)
{
$err = [
'code' => $this->getCode(),
'Msg' = & gt; $ this- & gt; getMessage (),
‘line’ => $this->getLine()
];
If ($type == 1) {
return json_encode($err);
}
return }
}

try
{
If ($_GET['age'] > 100) {
throw new proException('Customized exception handling', 1002);
} else {
Throw new Exception('Exception handling of the system', 1002);
}
} catch (proException $e) {
$info = $e->getErrorInfo();
var_dump($info);
} catch (Exception $e) {
Echo $e->getMessage();
}

?age=110 Output: array(4) { ["code"]=> int(1002) ["msg"]=> string(24) "Customized exception handling" ["file"]=> string(17) "/data/mi/demo.php" ["line"]=> int(64) }
?age=20 Output: System exception handling.

Logging//Disable error output error_reporting(0); //Set error handler
set_error_handler('errorHandler');
//Function to run at the end of the script
register_shutdown_function('fatalErrorHandler');

/**
* Error handling
* @param int $err_no Error code
* @param string $err_msg Error message
* @param string $err_file Error file
* @param int $err_line Error line number
* @return string
*/
function errorHandler($err_no = 0, $err_msg = '', $err_file = '', $err_line = 0)
{
$log = [
'['.date('Y-m-d h-i-s').']',
'|',
$err_no,
'|',
$err_msg,
'|',
$err_file,
'|',
$err_line
];
$log_path = '/data/mi/test.txt';
error_log(implode(' ',$log)."rn",3, $log_path);
//echo implode(' ',$log)."
";
}

/**
* Catching fatal errors
* @return string
*/
function fatalErrorHandler() {
$e = error_get_last();
Switch ($e['type']) {
Case 1:
errorHandler($e['type'], $e['message'], $e['file'], $e['line']);
break;
}
}

class DemoClass_1
{
Public function index()
{
//A warning error occurs here, start errorHandler
echo $undefinedVarible;
}
}

$demo_1 = new DemoClass_1();
//A warning error occurred here and was captured by errorHandler
$demo_1->index();
//A fatal error occurs and the script stops running and triggers fatalErrorHandler
$demo_2 = new DemoClass_2();
$demo_2->index();

After turning on echo, output:
[2016-08-07 09-01-34] | 8 | Undefined variable: undefinedVarible | /data/mi/demo.php | 126
[2016-08-07 09-01-34] | 1 | Class 'DemoClass_2' not found | /data/mi/demo.php | 134
Remarks:
1. register_shutdown_function can also be used in API debugging to record each request value and return value to facilitate debugging.
2. The advantage of using "|" to split is that it is convenient to use awk to split the log.

Source: http://mp.weixin.qq.com/s?__biz=MjM5NDM4MDIwNw==&mid=2448834645&idx=1&sn=32c96f1344a270755a8e33a6f7ddc1e8#rd

For more [dry information sharing], please follow my personal subscription account.

Catch and handle PHP exceptions

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!