所以我刚开始使用苗条的 PHP 框架,我有点困惑。如文档中所述: https ://www.slimframework.com/docs/v4/middleware/error-handling.html#adding-custom-error-handlers
这应该添加某种错误处理。
所以我测试了那个代码:
<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
use Psr\Log\LoggerInterface;
require __DIR__ . '/vendor/autoload.php';
$app = AppFactory::create();
// Add Routing Middleware
$app->addRoutingMiddleware();
// Define Custom Error Handler
$customErrorHandler = function (
Request $request,
Throwable $exception,
bool $displayErrorDetails,
bool $logErrors,
bool $logErrorDetails,
?LoggerInterface $logger = null
) use ($app) {
$logger->error($exception->getMessage());
$payload = ['error' => $exception->getMessage()];
$response = $app->getResponseFactory()->createResponse();
$response->getBody()->write(
json_encode($payload, JSON_UNESCAPED_UNICODE)
);
return $response;
};
// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware(true, true, true);
$errorMiddleware->setDefaultErrorHandler($customErrorHandler);
$app->get('/', function (Request $request, Response $response, $args) {
$test = [];
$foo = $test['nada'];
$response->getBody()->write("Hello world!");
return $response;
});
$app->run();
现在,当我调用未定义的路线时,例如
localhost:8000/this/route/doenst/exist
或者只是让一些错误的代码运行(从数组访问未定义的键)
localhost:8000/
我只是得到“普通”错误
所以我想我的问题是:如何实现一个错误处理程序来处理编码错误或调用未定义的路由?