【问题标题】:Redirecting with error on Slim Framework在 Slim 框架上重定向错误
【发布时间】:2017-04-25 13:09:00
【问题描述】:

我想根据我网站中表单中的信息重定向到一个页面(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 或任何你想调用的文件)的文件中。

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

【问题讨论】:

  • @MikaTuupola 我编辑了我的问题,因为您放置的链接没有帮助。不过还是谢谢!

标签: php slim slim-3


【解决方案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;

}

希望对你有帮助

【讨论】:

  • 不过,这仅适用于 404。我想处理自定义错误或提供自定义消息以及我抛出的任何错误。
  • 这看起来好多了,但是如何在我的代码中实现它呢?我是否将它保存为一个类并调用它,给它我想抛出的错误代码?
【解决方案2】:

您可以为 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>

【讨论】:

    猜你喜欢
    • 2016-03-08
    • 1970-01-01
    • 2015-09-07
    • 2017-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多