1.简单异常抛出

<?php
namespace app\api\model;
use think\Exception;

class Banner
{
    public static  function getBannerByID($id){
        //TODO 根据Banner  ID号 获取Banner信息
        try{
            1 / 0;
        }
        catch (Exception $ex)
        {
            //TODO;可以记录日志,正式项目将异常抛给客户端意义不大,最终还是需要服务器端做分析处理
            throw $ex;
        }
        return "This is banner test";
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
<?php 
namespace app\api\controller\v1;
use think\Exception;
//use think\Validate;
//use app\api\validate\BaseValidate;
//use app\api\validate\TestValidate;
use app\api\validate\IdIsInt;
use app\api\model\Banner as BannerModel;
class Banner {
	/**
	 * 获取指定id的banner信息
	 * @url /banner/:id
	 * @http GET
	 * @id banner的id的号
	 * 
	 */
	public function getBanner($id)
	{
	    //正常情况下,3句话搞定
		(new IdIsInt())->goCheck();
        //直白的异常处理方式,但是代码不能复用,不能完美的服务大型项目
        try
        {
            $banner = BannerModel::getBannerByID($id);
        }catch (Exception $ex)
        {
            $err = [
                'error_code' => 10001,
                'msg' => $ex->getMessage()
            ];
            return json($err,400);
            //tp5需要使用json()转为json格式再返回
            //Postman 出现200状态,不是指成功的响应,而是成功的拿到了你想要的结果
        }
 }

第六章 笔记(异常处理)

相关文章: