我想重定向到一个页面(error.php,或者可能是 404/406.php,无论错误是什么),具体取决于我网站中表单中的信息。我设法记录了这样的错误:
if ($date > $curdate) {
return $response
->withStatus(406)
->withHeader('Content-Type', 'text/html')
->write('You can\'t select dates in the future!');
}
我怎样才能做到这一点sends您是否特别访问了包含该错误的页面,而不是在网络选项卡中记录/请求它?
编辑进一步解释: 现在我明白了:
Request URL:http://raspberrypi/chartAPI/api/{id}/{date1}/{date2}
Request Method:POST
Status Code:406 Not Acceptable
Remote Address:192.168.0.80:80
Referrer Policy:no-referrer-when-downgrade
这几乎按预期工作。我想做的就是它把我送到“http://raspberrypi/chartAPI/error/406 http://raspberrypi/chartAPI/error/406“(例如),并显示名为 406.php(或 error406.php 或任何您想要的名称)的文件中的内容。
Edit2:我现在设法用这个做一些事情:
return $response->withRedirect("error.php");
但我明白了:
Request URL:http://raspberrypi/chartAPI/api/{id}/{date1}/error.php
Request Method:GET
Status Code:405 Method Not Allowed
slim 抛出这个错误:
Method not allowed. Must be one of: POST
为什么要删除 {date2}?为什么它要求 POST 方法?
您可以像这样扩展 Not Found 类
<?php
namespace App\Action;
use Slim\Handlers\AbstractHandler;
use Slim\Views\Twig;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
class CustomErrorHandler extends AbstractHandler {
private $view;
public function __construct(Twig $view) {
$this->view = $view;
}
public function __invoke(ServerRequestInterface $request, ResponseInterface $response) {
parent::__invoke($request, $response);
$status = $response->getStatusCode();
$this->view->render($response, $status . '.twig');
return $response->withStatus($status);
}
借助 Slim v3、PSR-7 和中间件,上述所有操作都可以通过几行代码完成:
// $c is the DI container of Slim
$app->add(function ($request, $response, $next) use ($c) {
// First execute anything else
$response = $next($request, $response);
// Have multiple if's for each status code or use a switch based on $response->getStatusCode()
if (404 === $response->getStatusCode()) {
// A 404 should be invoked
$handler = $c['customErrorHandler'];
return $handler($request, $response);
}
// Any other request, pass on current response
return $response;
}
希望这可以帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)