首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从一个错误了解Exception的继承关系

背景

自己写了一个全局异常处理类 ExceptionHandler,继承exception\Handler

重写了Handle render 方法

ExceptionHandler.php

public functionrender(Exception$e)

{

if($einstanceofBaseException) {

// 自定义异常

$this->code=$e->code;

$this->msg=$e->msg;

$this->errorCode=$e->errorCode;

}else{

// 如果是调试模式就显示具体错误页面

if(config('app_debug')) {

return parent::render($e);

}else{

$this->code=500;

$this->msg='服务器错误';

$this->errorCode=999;

$this->recordErrorLog($e);

}

}

$request=newRequest();

$result= [

'msg'=>$this->msg,

'error_code'=>$this->errorCode,

'request_url'=>$request::url()

];

returnjson($result,$this->code);

}

当我访问一个不存在的接口或给PHP制造一个异常时(例

:return$banner;) $baner 类型为

array,PHP会显示以下错误

( ! ) Fatal error: Uncaught exception 'think\exception\ErrorException' with message 'Argument 1 passed to app\lib\exception\ExceptionHandler::render() must be an instance of think\Exception, instance of InvalidArgumentException given, called in C:\xampp\htdocs\myblog\thinkphp\library\think\Error.php on line 50 and defined' in \xxx\ExceptionHandler.php on line 33

( ! ) think\exception\ErrorException: Argument 1 passed to app\lib\exception\ExceptionHandler::render() must be an instance of think\Exception, instance of InvalidArgumentException given, called in xxx\thinkphp\library\think\Error.php on line 50 and defined in \xxx\ExceptionHandler.php on line 33

在调用ExceptionHandler::render()的时候,本来应该接收一个think\Exception的参数,但是TP框架传递给我们一个HttpException类型的参数,这说明HttpException不能自动的转换为think\Exception类型,如果HttpException能自动转换为think\Exception,HttpException应该为think\Exception的一个子类。

Exception继承关系图

这说明think\Exception 和HttpException 两者之间没有直接的联系,他们并不是一个父子类的关系,所以当你尝试把HttpException 传递到 think\Exception 的时候就会报以上的错误。

那么,我们如何来解决这样的问题呢?

思路:我们需要找到think\Exception 和HttpException 共同的父类,来作为参数的类型.

使用基类 \Exception 作为参数的类型

public functionrender(\Exception$e)

{

if($einstanceofBaseException) {

// 自定义异常

$this->code=$e->code;

$this->msg=$e->msg;

$this->errorCode=$e->errorCode;

}else{

// 如果是调试模式就显示具体错误页面

if(config('app_debug')) {

return parent::render($e);

}else{

$this->code=500;

$this->msg='服务器错误';

$this->errorCode=999;

$this->recordErrorLog($e);

}

}

$request=newRequest();

$result= [

'msg'=>$this->msg,

'error_code'=>$this->errorCode,

'request_url'=>$request::url()

];

returnjson($result,$this->code);

}

private functionrecordErrorLog(\Exception$e)

{

Log::init([

'type'=>'File',

'level'=> ['error']

]);

Log::record($e->getMessage(),'error');

}

再次刷新页面后,正确显示异常错误信息

  • 发表于:
  • 原文链接http://kuaibao.qq.com/s/20180416G1H3FB00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券
http://www.vxiaotou.com