发现问题: PHP7的异常通过try{}catch(){}
无法抓取到。
查看手册发现:不同于传统(PHP 5)的错误报告机制,现在大多数错误被作为 Error 异常抛出。
Error
类并非继承自 Exception
类,所以不能用 catch (Exception $e) { ... }
来捕获Error
。你可以用 catch (Error $e) { ... }
,或者通过注册异常处理函数( set_exception_handler()
)来捕获Error
。
1.Error 层次结构
- Throwable
- Exception
- Error
- ArithmeticError
- DivisionByZeroError
- AssertionError
- ParseError
- TypeError
- ArithmeticError
示例
#php 7.1
try {
$result = eval("return 1+k;");
} catch (Throwable $e) { //此处通过Exception是无法抓取到错误的
//do sth
}
2.Exception类定义
Exception {
/* 属性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 方法 */
public __construct ([ string $message = "" [, int $code = 0 [, Throwable $previous = NULL ]]] )
final public string getMessage ( void )
final public Throwable getPrevious ( void )
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )
final public string getTraceAsString ( void )
public string __toString ( void )
final private void __clone ( void )
}
示例
抓取异常后,排查问题比较有用的方法
try {
} catch(Exception $e) {
//查看错误抛出时的调用栈
print_r($e->getTrace());
//查看异常所在文件及行数
print_r($e->getFile().$e->getLine());
}