Home > php教程 > php手册 > Catch and handle PHP exceptions

Catch and handle PHP exceptions

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

Catch and handle PHP exceptions ~

The system comes with exception handling<?php<br /> header("Content-type:text/html;charset=utf-8");<br /> try<br /> {<br /> //Exception thrown when business processing error occurs. <br /> $age = 130;<br /> If ($age > 120) {<br>                                                        throw new Exception('Age cannot be greater than 120 years old.', 1001);<br> }<br> } catch (Exception $e) {<br> $err = [<br> ‘code’ => $e->getCode(),<br> ‘msg’ => $e->getMessage(),<br> 'file' => $e->getFile(),<br> 'line' => $e->getLine()<br> ];<br> Echo json_encode($err);<br> }<br> <br> Output: {"code":1001,"msg":"u5e74u9f84u4e0du80fdu5927u4e8e120u5c81u3002","file":"/data/mi/demo.php","line":11}Custom exception handling<?php <br /> header("Content-type:text/html;charset=utf-8");<br /> class proException extends Exception<br /> {<br /> //Customize the method according to business needs<br /> /**<br /> * Get error message<br /> * @param int $type type 1=json 2=array<br /> * * @return array<br /> ​​*/<br /> Public function getErrorInfo($type = 2)<br /> {<br />          $err = [<br /> ‘code’ => $this->getCode(),<br> 'Msg' = & gt; $ this- & gt; getMessage (), <br>                                                                                                                                                                                                                   ‘line’ => $this->getLine()<br> ];<br> If ($type == 1) {<br>                    return json_encode($err);<br>         }<br> return }<br> }<br> <br> try<br> {<br> //Exception thrown when business processing error occurs. <br> $age = 130;<br> If ($age > 120) {<br>                                               throw new proException('Age cannot be greater than 120 years old.', 1001);<br> }<br> } catch (proException $e) {<br> $info = $e->getErrorInfo();<br> var_dump($info);<br> }<br> <br> 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) }<br><br>Catch multiple exceptions header("Content-type:text/html;charset=utf-8"); class proException extends Exception<br /> {<br /> //Customize error methods according to business needs<br /> <br /> /**<br /> * Get error message<br /> * @param int $type type 1=json 2=array<br /> * * @return array<br /> ​​*/<br /> Public function getErrorInfo($type = 2)<br /> {<br />          $err = [<br />             'code' => $this->getCode(),<br> 'Msg' = & gt; $ this- & gt; getMessage (), <br>                                                                                                                                                                                                               ‘line’ => $this->getLine()<br> ];<br> If ($type == 1) {<br>                     return json_encode($err);<br>          }<br> return }<br> }<br> <br> try<br> {<br> If ($_GET['age'] > 100) {<br> ​​​​throw new proException('Customized exception handling', 1002);<br> } else {<br> Throw new Exception('Exception handling of the system', 1002);<br> }<br> } catch (proException $e) {<br> $info = $e->getErrorInfo();<br> var_dump($info);<br> } catch (Exception $e) {<br> Echo $e->getMessage();<br> }<br> <br> ?age=110 Output: array(4) { ["code"]=> int(1002) ["msg"]=> string(24) "Customized exception handling" ["file"]=> string(17) "/data/mi/demo.php" ["line"]=> int(64) }<br> ?age=20 Output: System exception handling. <br><br>Logging<b>//Disable error output</b> error_reporting(0);<code class="prettyprint linenums lang-php"> //Set error handler<br> set_error_handler('errorHandler');<br> //Function to run at the end of the script<br> register_shutdown_function('fatalErrorHandler');<br> <br> /**<br> * Error handling<br> * @param int $err_no Error code<br> * @param string $err_msg Error message<br> * @param string $err_file Error file<br> * @param int $err_line Error line number<br> * @return string<br> ​*/<br> function errorHandler($err_no = 0, $err_msg = '', $err_file = '', $err_line = 0)<br> {<br> $log = [<br>          '['.date('Y-m-d h-i-s').']',<br>         '|',<br>          $err_no,<br>         '|',<br>           $err_msg,<br>         '|',<br>           $err_file,<br>         '|',<br>           $err_line<br> ];<br> $log_path = '/data/mi/test.txt';<br> ​​error_log(implode(' ',$log)."rn",3, $log_path);<br> //echo implode(' ',$log)."<br>";<br> }<br> <br> /**<br> * Catching fatal errors<br> * @return string<br> ​*/<br> function fatalErrorHandler() {<br> $e = error_get_last();<br> Switch ($e['type']) {<br> Case 1:<br>            errorHandler($e['type'], $e['message'], $e['file'], $e['line']);<br>               break;<br> }<br> }<br> <br> class DemoClass_1<br> {<br> Public function index()<br>{<br> ​​​​//A warning error occurs here, start errorHandler<br> echo $undefinedVarible;<br> }<br> }<br> <br> $demo_1 = new DemoClass_1();<br> //A warning error occurred here and was captured by errorHandler<br> $demo_1->index();<br> //A fatal error occurs and the script stops running and triggers fatalErrorHandler<br> $demo_2 = new DemoClass_2();<br> $demo_2->index();<br> <br> After turning on echo, output: <br> [2016-08-07 09-01-34] | 8 | Undefined variable: undefinedVarible | /data/mi/demo.php | 126<br> [2016-08-07 09-01-34] | 1 | Class 'DemoClass_2' not found | /data/mi/demo.php | 134Remarks:
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template