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(‘错误信息‘);
原文地址:https://www.cnblogs.com/lt-com/p/10087667.html
时间: 2024-10-18 02:58:48