当找不到记录时发送StatusCode 400"

时间:2017-01-07 01:38:43

标签: php slim

当MySql响应失败时,如何在slim v2中将StatusCode设置为400?

$app->get('/gg/:user/:pass', 'gg');

function gg($user, $pass) {
                $sql = "...";
                try {
                        $db = getDB();
                        $stmt = $db->prepare($sql);
                        $stmt->bindParam("user", $user);
                        $stmt->bindParam("pass", $pass);
                        $stmt->execute();
                        $gs = $stmt->fetchAll(PDO::FETCH_OBJ);
                        if ($gs) {
                            ....
                        } else {
                                http_response_code(400);
                                throw new PDOException('No records found.');
                        }
                } catch(PDOException $e) {
                        echo '{"error":{"text":'. $e->getMessage() .'}}';
                }
        }

api返回状态错误200,但是当没有找到mysql数据时,它应该更改为statuscode 400。

1 个答案:

答案 0 :(得分:1)

According to the slim2 manual the correct approach is:

$app->response->setStatus(400);

因为你需要在函数内部获取$app,所以有两种方法:

在这种情况下,我建议:http://docs.slimframework.com/configuration/names-and-scopes/

$app = Slim::getInstance();