php实现实例化类后自动进行错误以及异常处理(简易版)
<?php class App { public function __construct() { /* * ini_set 设置配置项 * display_errors 是否在页面显示错误信息 */ ini_set('display_errors', 0); $this->setSysHandler(); } public function setSysHandler() { //php中止时执行 register_shutdown_function([$this, 'fatalHandler']); //设置用户自定义的错误处理函数 set_error_handler([$this, 'errorHandler']); //设置用户自定义的异常处理函数 set_exception_handler([$this, 'exceptionHandler']); } // 错误被包装成为异常抛出 public function errorHandler($code, $msg, $file, $line) { throw new ErrorException($msg, $code, $code, $file, $line); } public function fatalHandler() { if ($errors = error_get_last()) { $msg = $errors['message']; $code = $errors['type']; $file = $errors['file']; $line = $errors['line']; echo "<font size='7'>:(</font><h2> 文件: {$file}; 行号: {$line};</h2>"; echo "<h4>错误信息: {$msg}; 错误代码: {$code}</h4>"; echo "<pre>"; } } public function exceptionHandler($excep) { $this->handler($excep); } public function handler($excep) { $msg = $excep->getMessage();//获取异常消息内容 $code = $excep->getCode();//获取异常代码 $file = $excep->getFile();//创建异常时的程序文件名称 $line = $excep->getLine();//获取创建的异常所在文件中的行号 $trace = $excep->getTrace();//获取异常追踪信息 $this->errorlog($msg, $code, $file, $line);//发送错误信息到某个地方 echo "<font size='7'>:(</font><h2> 文件: {$file}; 行号: {$line};</h2>"; echo "<h4>错误信息: {$msg}; 错误代码: {$code}</h4>"; echo "<pre>"; if ($excep instanceof ErrorException) { array_shift($trace); } print_r($trace); //函数的调用栈 } public function errorlog($msg, $code, $file, $line) { $str = date('Y-m-d H:i:s') . "\r\n"; $str .= "错误信息是:"; $str .= $msg; $str .= "\r\n"; $str .= "错误行号是:"; $str .= $line; $str .= "\r\n"; $str .= "错误代码是:"; $str .= $code; $str .= "\r\n"; $str .= "错误行文件:"; $str .= $file; $str .= "\r\n"; $str .= "\r\n"; error_log($str, 3, './myerror.log'); } } $app = new App();
原文链接:https://blog.csdn.net/qq_20025577/article/details/85059762
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了