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

  • Post author:
  • Post category:php


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 的问题。



版权声明:本文为qq_38287952原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。