目的:
1.添加CController,后续所有Controller继承该类,可以通过 fail/success 返回 json 格式的数据;
2.通过 gii 自动添加 model,这个很容易,记住修改 allowedIPs就可以;另外需要在 db.php 中添加 tablePrefix => 't_',然后在创建表的时候选中使用前缀;另外需要注意,preview并没有真正创建文件,要点击 generate 才能真正创建;
3.自定义异常处理,对于某种异常,修改为 json 返回
/**
* 定义自己的 Controller 类,后续所有 Controller 继承这个类,以便通过 fail 和 sucess 以及 throwException 抛出异常
*/
namespace app\custom;
use Yii;
use yii\web\Controller;
use yii\web\Response;
class CController extends Controller {
/**
* 自定义正确和错误返回
* @param $reply
*/
public function sucess($reply) {
$result = array('code' => 0, 'msg' => $reply);
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->data = $result;
Yii::$app->response->send();
}
/**
* 自定义正确和错误返回
* @param $reply
* @param int $errcode
*/
public function fail($reply, $errcode = 1) {
$result = array('code' => $errcode, 'msg' => $reply);
Yii::$app->response->data = $result;
Yii::$app->response->format = Response::FORMAT_JSON;
Yii::$app->response->send();
}
public function throwException($msg, $code = ErrorCode::ERR_PARAM_FORMAT) {
<span style="white-space:pre"> </span>throw new RunException($msg, $code);
}
}
/**
* 定义自己的异常类
*/
namespace app\custom;
class RunException extends \Exception {
}
/**
* 修改 web.php 中 errorHandler 为:
'errorHandler' => [
'errorAction' => 'site/error',
'class' => 'app\custom\MyErrorHandler',
],
即添加给 class,如下,实际上只是继承了默认的处理类 ErrorHandler
如果抛出的异常类型是自定义的,那么表示处理失败且应该显示异常字符串;
否则根据是否处于调试模式判断输出格式
*/
namespace app\custom;
use Yii;
use yii\web\ErrorHandler;
class MyErrorHandler extends ErrorHandler {
public function renderException($e)
{ if ($e instanceof RunException) { $result = array('code' => $e->getCode(), 'msg' => $e->getMessage()); echo json_encode($result); Yii::$app->end(); } if (YII_DEBUG) { Yii::error('*** catched exception'); parent::renderException($e); } else { $this->logException($e); $result = array('code' => ErrorCode::ERR_SYSTEM_ERROR, 'msg' => 'system is busy now, please try later'); echo json_encode($result); Yii::$app->end(); } }
/**
定义异常代码,用户返回的 code 值
*/
namespace app\custom;
use Yii;
class ErrorCode {
const ERR_FAIL = 1;
const ERR_PARAM_FORMAT = 2;
const ERR_PARAM_LOST = 3;
const ERR_SYSTEM_ERROR = 100;
}
然后可以测试了:
namespace app\controllers;
use app\custom\ErrorCode;
use Yii;
use app\custom\CController;
class TestController extends CController {
public function actionTest() {
// throw new \RuntimeException('abcd', 12);
// $this->throwException('abcd', ErrorCode::ERR_PARAM_FORMAT);
$this->sucess(array('a'=>1));
}
}