Php Slim框架上的带错误重定向
我想重定向到一个页面(error.php,或者404/406.php,无论错误是什么),这取决于我网站中表单中的信息。我设法记录了如下错误:Php Slim框架上的带错误重定向,php,slim,slim-3,Php,Slim,Slim 3,我想重定向到一个页面(error.php,或者404/406.php,无论错误是什么),这取决于我网站中表单中的信息。我设法记录了如下错误: if ($date > $curdate) { return $response ->withStatus(406) ->withHeader('Content-Type', 'text/html') ->write('You can\'t select dates in th
if ($date > $curdate) {
return $response
->withStatus(406)
->withHeader('Content-Type', 'text/html')
->write('You can\'t select dates in the future!');
}
我该如何做才能让它将您发送到带有该错误的页面,而不是在“网络”选项卡中记录/请求该错误
编辑进一步解释:现在我了解到:
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
Request URL:http://raspberrypi/chartAPI/api/{id}/{date1}/error.php
Request Method:GET
Status Code:405 Method Not Allowed
这几乎达到了预期效果。我想做的是将我发送到“”(例如),并在一个名为406.php(或error406.php或任何您想调用的文件)的文件中显示内容
Edit2:我现在设法做了一些事情:
return $response->withRedirect("error.php");
但我明白了:
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
Request URL:http://raspberrypi/chartAPI/api/{id}/{date1}/error.php
Request Method:GET
Status Code:405 Method Not Allowed
斯利姆抛出了这个错误:
Method not allowed. Must be one of: POST
为什么要删除{date2}?为什么它需要一个POST方法呢?您可以像这样扩展NotFound类
<?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创建自己的异常处理程序,并为处理程序创建一个要解析的错误数组。当您将它注入到新的Slim实例中时,它将处理您抛出的任何异常 模板:
<h1>Whoops!</h1>
<p>{{ code }} : {{ message }}</p>
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
哇!
{{code}}:{{message}
-
{错误%中的错误为%0}
- {{error}} {%endfor%}
不过,这只适用于404。我想处理自定义错误或提供自定义消息以及抛出的任何错误。这看起来更好,但如何在代码中实现它?我是否将其保存为类并调用它,并给出我想要抛出的错误代码?可能是@MikaTuupola的重复我编辑了我的问题,因为您放置的链接没有帮助。不过还是要谢谢你!