[英]Return http 500 with Slim framework
如果我的API中的某些东西变坏了我想要返回一个http 500请求。
$app = new Slim();
$app->halt(500);
它仍然返回一个http 200。
如果我运行此代码:
$status = $app->response()->status();
echo $status; //Here it is 200
$status = $app->response()->status(500);
echo $status; //Here it is 500
它仍然给我一个http 200
$app->response()->status(500);
是正确的,请参阅此处的文档。
检查以确保您正在调用$app->run();
设置状态后,这将准备并输出响应代码,标题和正文。
编辑 ,确保定义路由或Slim将输出404响应,这有效:
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->response()->status(500);
$app->get('/', function () {
// index route
});
$app->run();
如果有人仍然有这个问题,这就是我最终做的事情:
设置错误处理程序
$app->error(function (Exception $exc) use ($app) { // custom exception codes used for HTTP status if ($exc->getCode() !== 0) { $app->response->setStatus($exc->getCode()); } $app->response->headers->set('Content-Type', 'application/json'); echo json_encode(["error" => $exc->getMessage()]); });
然后,只要您需要返回特定的HTTP状态,就会抛出包含状态代码的异常:
throw new Exception("My custom exception with status code of my choice", 401);
(在Slim论坛上找到它)
如果你必须在$ app-> run()之后推送标题,你总是可以依赖标题php函数:
header('HTTP/1.1 401 Anonymous not allowed');
超薄框架v2 维基状态
require 'Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get('/', function () use ($app) {
$app->response()->setStatus(500);
$app->response()->setBody("responseText");
return $app->response();
});
$app->run();
要么
$app->get('/', function () use ($app) {
$app->halt(500, "responseText");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.