thinkphp error () 方法 和 try catch 出现的问题。

本文详细解析了在PHP中使用error()方法时遇到的问题,即当用户名密码错误时返回为空的情况。通过深入分析HttpResponseException类及异常处理流程,提出了两种解决方案:一是修改error()方法和HttpResponseException类,二是利用自定义异常处理。最终,通过实践验证了解决方案的有效性。

 1、在学习的过程中,遇到了一个问题当用户名密码错误的时候:返回的为空。

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());
}

正常的逻辑返回的应该是

 

   那么是为什么呢?

  那么我们看 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;
    }

}

   这里就要明白 php 的异常处理是如何执行的。

   只有当php的语法错误,才会自动把错误信息给 Exception中的 $message

  这里的是程序上的逻辑判断错误,并没有交给Exception 的 $message。

  当执行到 throw new HttpResponseException($response); ,就直接执行到了 catch 中的 Exception类。

  通过上面的分析,那么$message没有了值,那么返回的自然就是空的了。

 

二、验证一下

  1、error() 方法中修改

throw new HttpResponseException($response);

 
throw new HttpResponseException($response, $msg);

 2 、HttpResponseException 类中修改 __construct() 

 

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

 这里我自动把错误信息给到了 Exception类。

 结果是正确,验证我的想法。

 那么我们不需要改动源码,可以在控制器这样写:

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());
}

 完美的解决了 error()和 Exception 的问题。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值