码迷,mamicode.com
首页 > Web开发 > 详细

PHP (Yii2) 自定义业务异常类(可支持返回任意自己想要的类型数据)

时间:2018-12-08 15:38:33      阅读:340      评论:0      收藏:0      [点我收藏+]

标签:row   ret   status   字符串   throw   tor   span   pst   parent   

public function beforeAction($action)
    {
        return parent::beforeAction($action);
    }

    public function runAction($id, $params = [])
    {
        try {
            return parent::runAction($id, $params);
        } catch (MyException $myException) {
            //此处返回业务错误 比如返回json字符串错误
            $result = [
                ‘status‘ => $myException->getCode(),
                ‘message‘ => $myException->getMessage(),
                ‘data‘ => null
            ];
            return json_encode($result, true);

        } catch (\Exception $ex) {
            throw  $ex;
        }
    }

    public function afterAction($action, $result)
    {
        return parent::afterAction($action, $result);
    }

异常类(只需要继承基础的异常类即可)

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/8 0008
 * Time: 14:38
 */

namespace app\librarys;


class MyException extends \Exception
{

}

 

可以在任意地方使用,不需要再写返回值,自动返回。

throw new MyException(‘错误信息‘);

 

PHP (Yii2) 自定义业务异常类(可支持返回任意自己想要的类型数据)

标签:row   ret   status   字符串   throw   tor   span   pst   parent   

原文地址:https://www.cnblogs.com/lt-com/p/10087667.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!