在公用工具類寫異常類php
<?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
$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 ide
分別存放錯誤碼和錯誤信息工具
ErrorCode.phpui
<?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.phpthis
<?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()); } } }