在公用工具类写异常类
<?php namespace Brady\Tool\Exception; use Brady\Tool\Constant\ErrorMsg; use \Exception; class ExceptionResult extends Exception { const DEFAULT_CODE = 500; protected static $messageTemplate = []; public static function setMsgTemplate(array $template = []) { static::$messageTemplate = $template; } public static function getMsgTemplate() { return static::$messageTemplate; } public function errorMsg() { return "异常信息:文件-".$this->getFile()." 行号-".$this->getLine()."错误码-".$this->getCode()." 信息-".$this->getMessage(); } /** * @param $code * @param bool $isChinese 是否直接抛出中文 */ public static function throwException($code,$isChinese = false) { $class = __CLASS__; if($isChinese){ throw new $class($code,500); } else { //根据code获取msg $msg = static::getMsg($code); throw new $class($msg,$code); } } public static function getMsg($code) { $template = self::getMsgTemplate(); if(isset($template[$code])){ return $template[$code]; } else { $class = __CLASS__; throw new $class("错误码未设置".$code); } } }
lumen bootstrp的app里面注册服务提供者
$app->register(App\Providers\ExceptionServiceProvider::class);
providers文件夹下新建文件
<?php /** * Created by PhpStorm. * User: costa * Date: 2019/3/15 * Time: 14:12 */ namespace App\Providers; use Brady\Tool\Exception\ExceptionResult; use Illuminate\Support\ServiceProvider; class ExceptionServiceProvider extends ServiceProvider { /** * 注册编码信息 */ public function register() { $tpl = require (dirname(__DIR__) . '/Constants/ErrorMsg.php'); ExceptionResult::setMsgTemplate($tpl); } }
app目录下新建目录 Constants
分别存放错误码和错误信息
ErrorCode.php
<?php /** * Created by PhpStorm. * User: costa * Date: 2019/3/15 * Time: 14:23 */ namespace App\Constants; class ErrorCode { /** * 基本错误码 */ const SUCCESS = 200; const UNAUTHORIZED = 401; const FAIL = 500; }
ErrorMsg.php
<?php /** * Created by PhpStorm. * User: costa * Date: 2019/3/15 * Time: 14:22 */ namespace App\Constants; return [ ErrorCode::SUCCESS => '成功' , ErrorCode::UNAUTHORIZED => '暂无权限!' , ErrorCode::FAIL => '失败' , ];
使用 在控制器里面
<?php namespace App\Service; //服务层 use App\Constants\ErrorCode; use App\Repository\UserRepository; use Brady\Tool\Exception\ExceptionResult; use Mockery\Exception; class UserService { public $userRepository; public function __construct() { $this->userRepository = new UserRepository(); } public function queryUserList($where) { $where = ['name'=>"brady"]; return $this->userRepository->getList($where); } public function getUserInfo($id) { try{ ExceptionResult::throwException(ErrorCode::UNAUTHORIZED); return $this->userRepository->getById($id); } catch (\Exception $e){ var_dump($e->getMessage()); } } }