替换notFoundHandler设置

时间:2019-08-25 17:08:30

标签: php slim slim-4

我正在从Slim / 3迁移到Slim / 4。我发现或想出了我正在使用的所有功能的替代品,这些功能已被删除,除了404 Not Found Handler(属于现在App::$settings的一部分):

  

Slim App::$settings已被删除,实现了多个中间件以替换每个单独设置中的功能。

是否有notFoundHandler的中间件?如果没有,我该如何实施?

我的过去看起来像这样:

use Slim\Container;
$config = new Container(); 
$config['notFoundHandler'] = function (Container $c) {
    return function (Request $request, Response $response) use ($c): Response {
        $page = new Alvaro\Pages\Error($c);
        return $page->notFound404($request, $response);
    };
};

1 个答案:

答案 0 :(得分:4)

根据Slim 4 documentation on error handling

  

每个Slim Framework应用程序都有一个错误处理程序,该错误处理程序接收所有   未捕获的PHP异常

您可以设置一个自定义错误处理程序来处理所引发的每种类型的异常。在同一页面上提供了预定义异常类的列表。

这是一个非常基本的示例,说明如何将 closure 注册为错误处理程序,以仅处理HttpNotFoundException异常。您也可以将处理程序放在扩展Slim\Handlers\ErrorHandler的类中。另外,我实际上并没有使用您的Alvaro\Pages\Error来生成响应,但是更改它应该是僵硬的:

<?php

require '../vendor/autoload.php';

$app = Slim\Factory\AppFactory::create();

// Define Custom Error Handler
$customErrorHandler = function (
    Psr\Http\Message\ServerRequestInterface $request,
    \Throwable $exception,
    bool $displayErrorDetails,
    bool $logErrors,
    bool $logErrorDetails
) use ($app) {
    $response = $app->getResponseFactory()->createResponse();
    // seems the followin can be replaced by your custom response
    // $page = new Alvaro\Pages\Error($c);
    // return $page->notFound404($request, $response);
    $response->getBody()->write('not found');
    return $response->withStatus(404);
};

// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
// Register the handler to handle only  HttpNotFoundException
// Changing the first parameter registers the error handler for other types of exceptions
$errorMiddleware->setErrorHandler(Slim\Exception\HttpNotFoundException::class, $customErrorHandler);


$app->get('/', function ($request, $response) {
    $response->getBody()->write('Hello Slim 4');
    return $response;
});

$app->run();

另一种方法是创建一个通用错误处理程序,并将其注册为默认处理程序,然后在该处理程序中,根据引发的异常类型决定应发送的响应。像这样:

$customErrorHandler = function (
    Psr\Http\Message\ServerRequestInterface $request,
    \Throwable $exception,
    bool $displayErrorDetails,
    bool $logErrors,
    bool $logErrorDetails
) use ($app) {
    $response = $app->getResponseFactory()->createResponse();

        if ($exception instanceof HttpNotFoundException) {
            $message = 'not found';
            $code = 404;
        } elseif ($exception instanceof HttpMethodNotAllowedException) {
            $message = 'not allowed';
            $code = 403
        }
        // ...other status codes, messages, or generally other responses for other types of exceptions

    $response->getBody()->write($message);
    return $response->withStatus($code);
};

然后,您可以将其设置为默认错误处理程序:

$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);