【发布时间】:2017-09-11 03:34:34
【问题描述】:
好吧,我很困惑。我正在使用 Slim 框架,并且我有以下代码:
1 $app->post("/user/login", function (Request $request, Response $response) {
2 $resp = null;
3 try {
4 if (!array_key_exists("password", $request->getParams()) || !array_key_exists("username", $request->getParams())) {
5 throw new LiberInvalidRequestException("Not all required parameters were passed.");
6 }
7 $user = new User($this->db, [
8 'username' => $request->getParam('username'),
9 'password' => $request->getParam('password')
10 ]);
11 try {
12 $resp['logincode'] = $user->login();
13 $resp['success'] = true;
14 } catch (LiberAuthenticationException $exception) {
15 $resp['success'] = false;
16 $resp['errormessage'] = $exception->getMessage();
17 }
18 } catch (LiberInvalidRequestException $exception) {
19 $resp['success'] = false;
20 $resp['errormessage'] = $exception->getMessage();
21 } finally {
22 return $response->withJson($resp);
23 }
24 });
当我用正确的参数调用这条路线时,我得到一个null 响应。在我看来,这不应该是可能的,因为在所有可能的情况下,某些东西都分配给了$resp。当我使用调试器执行此函数时,我可以一直运行到第 12 行,然后调试器会跳转到 finally 块(第 22 行)。
这怎么可能?执行不应该继续还是转到catch块?
【问题讨论】:
-
如果抛出
LiberAuthenticationException或LiberInvalidRequestException以外的一些异常,可能会出现...命名空间问题? -
@deceze 我认为没有抛出另一个异常。我发现执行跳转到finally块的点是composer autoloader中的一个include语句。包含语句不会抛出异常 IIRC。
-
try内的try只会增加混乱。请参阅 this 帖子,了解如何为单个try编写多个catch块 - 如果需要的话。 -
@DhruvSaxena 您发布链接的问题是关于如何在一个块中编写多个捕获。我有多个尝试块做不同的事情。我也不认为这与我的问题有很大关系。
标签: php try-catch try-catch-finally