在Slim Framework上重定向错误

时间:2017-04-25 13:09:01

标签: 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 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

这几乎按预期工作。我想做的是把它送到" http://raspberrypi/chartAPI/error/406" (例如),并将内容显示在名为406.php(或error406.php或您想要调用的任何内容)的文件中。

编辑2:我现在用以下方式管理过:

return $response->withRedirect("error.php");

但我明白了:

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方法?

2 个答案:

答案 0 :(得分:1)

您可以像这样扩展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 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;

}

希望这有帮助

答案 1 :(得分:1)

您可以为Slim创建自己的异常处理程序,并为要解析的处理程序创建一个错误数组。当您将其注入新的Slim实例时,它将处理您抛出的任何异常。

Slim Error Handler Docs

$slimErrorHandler = new Slim\Container;

// exception handler
$slimErrorHandler['errorHandler'] = function() {
    return function($request,$response,$exception) {
        $exceptionMessage = $exception->getMessage();
        $json = (array)json_decode($exceptionMessage);
        $error = array(
            'message' => $json['message'],
            'code' => $exception->getCode(),
            'errors' => (array)$json['errors']
        );

        $view = new Slim\Views\Twig(__DIR__);
        return $view->render($response,'error.html',$error);
    };
};

// page not found handler
$slimErrorHandler['notFoundHandler'] = function () {
    return function ($request,$response) {
        return $response->write('Page not found!');
    };
};

$app = new Slim\App($slimErrorHandler);

$app->get('/',function($request,$response) {
    $error = array(
        'message' => "Errors were found:",
        'errors' => array(
            "email" => "Please enter a valid email",
            "date" => "You can't select dates in the future!"
        )
    );

    throw new Exception(json_encode($error),409);
});

$app->run();

模板:

<h1>Whoops!</h1>

<p>{{ code }} : {{ message }}</p>

<ul>
    {% for error in errors %}
        <li>{{ error }}</li>
    {% endfor %}
</ul>