以下4段代码为我在waylife项目中的简单应用(非生产环境),不健壮也不美化,但该SNS项目早已经夭折。
1、异常类的层级关系:
- class NotFoundException extends Exception{}
- class InputException extends Exception{}
- class DBException extends Exception{}
2、配置未捕捉异常的处理器:
- function exception_uncaught_handler(Exception $e) {
- header('Content-type:text/html; charset=utf-8');
- if ($e instanceof NotFoundException)
- exit($e->getMessage());
- elseif ($e instanceof DBException)
- exit($e->getMessage());
- else
- exit($e->getMessage());
- }
- set_exception_handler('exception_uncaught_handler');
3、在数据库连接代码,手动抛出DBException异常但未使用try…catch进行捕获处理,该异常将被PHP自定义异常处理器exception_uncaught_handler()函数处理:
- $this->resConn = mysql_connect ($CONFIGS['db_host'], $CONFIGS['db_user'], $CONFIGS['db_pwd']);
- if (false == is_resource($this->resConn))
- throw new DBException('数据库连接失败。'.mysql_error($this->resConn));
4、业务逻辑一瞥:
- if (0 != strcmp($curAlbum->interest_id, $it))
- throw new NotFoundException('很抱歉,你所访问的相册不存在');
以上就是PHP自定义异常处理器的具体使用方法。
![php中文网最新课程二维码](/static/images/article_wechat2021.jpg?1111)
声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理
网友评论
文明上网理性发言,请遵守 新闻评论服务协议
我要评论