异常分类
异常是按照层级处理的,如何a调用b,在b中发生异常,正常流程是b会把异常抛给a,a如果也有try捕获异常操作,便会在a中处理。下面基于RestFul API 给客户端返回正常的错误码格式来粗略讲解异常处理机制。
- 控制器文件:
<?php
/**
* Created by PhpStorm.
* User: chenzhitao
* Date: 2017/5/7
* Time: 下午1:49
*/
namespace app\api\controller\v1;
use app\api\validate\IDMustBePositiveInt;
use think\Exception;
use think\Validate;
use app\api\model\Banner as BannerModel;
class Banner
{
public function getBanner($id){
(new IDMustBePositiveInt())->goCheck();
try{
$banner = BannerModel::getBannerByID($id);
}catch (Exception $e){
$error = [
'error_code'=>10001,
'msg'=>$e->getMessage(),
];
return json($error,400);
}
return $banner;
}
}
- model文件,自制1/0异常,发现并抛出异常
<?php
/**
* Created by PhpStorm.
* User: chenzhitao
* Date: 2017/5/8
* Time: 下午2:15
*/
namespace app\api\model;
use think\Exception;
class Banner
{
public static function getBannerByID($id){
//TODO:根据banner ID号,获取Banner信息
try{
1 / 0;
}catch (Exception $e){
//TODO 记录日志
throw $e;
}
return 'this is banner';
}
}
- 客户端返回结果
{"error_code":10001,"msg":"Division by zero"}