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

被折叠的 条评论
为什么被折叠?



