亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定

在 php開發高可用高安全的app后端 (后臺登錄時候的一個問題)

標簽:
PHP ThinkPHP

1、当在登录页面输入不存在的用户名密码时提交时返回以下结果,那么是为什么呢?

https://img1.sycdn.imooc.com//5bc959790001901c03150197.jpg

  2、代码分析

try {
   // 判定username password
   $user = model('AdminUser')->get(['username' => $data['username']]);
   if (!$user || $user->status != config('code.status_normal')) {
       $this->error('该用户不存在');
   }
} catch (\Exception $e) {
   $this->error($e->getMessage());
}


这里程序走到了 $this->error('该用户不存在'); 那么我们看源码里有这样一段代码

throw new HttpResponseException($response);
class HttpResponseException extends \RuntimeException
{
    /**
     * @var Response
     */
    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    public function getResponse()
    {
        return $this->response;
    }
    
}

这里的 HttpResponseException 继承了 RuntimeException类,而RuntimeException类 继承了Exception类。这里需要php的异常处理的基础知识。

当php的语法错误或者内部错误的时候,会自动给到Exception中的 $message属性,而我们这里是程序上的逻辑错误,并没有给到 $message。

当执行到 HttpResponseException 的时候,就会直接走 catch 中的Exception,自然就是空值了。

 3、验证一下

   把 

 throw new HttpResponseException($response);

   修改为

throw new HttpResponseException($response, $msg);

 

HttpResponseException 类中构造方法修改为
public function __construct(Response $response, $message)
{
    $this->response = $response;
    $this->message = $message;
}

执行代码:

https://img1.sycdn.imooc.com//5bc95dde000112a502960241.jpg

  知道了是为什么?那么我们不需要修改源码,可以这样写:

try {
   // 判定username password
   $user = model('AdminUser')->get(['username' => $data['username']]);
   if (!$user || $user->status != config('code.status_normal')) {
      //exception('该用户不存在'); // 方式1。
      //throw new Exception('该用户不存在');// 方式2.
   }
} catch (\Exception $e) {
   $this->error($e->getMessage());
}


點擊查看更多內容
1人點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優質文章

正在加載中
PHP開發工程師
手記
粉絲
11
獲贊與收藏
1

關注作者,訂閱最新文章

閱讀免費教程

感謝您的支持,我會繼續努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學

大額優惠券免費領

立即參與 放棄機會
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號

舉報

0/150
提交
取消