【发布时间】:2019-03-30 12:03:31
【问题描述】:
我想覆盖 Slim 3 中的默认错误处理程序并使用 JSON 而不是默认的 HTML 页面进行响应。但我无法让它工作,我的自定义处理程序被完全忽略,我不知道为什么。
我的项目结构如下:
api/
public/
index.php
src/
config/
database.php
handlers.php
settings.php
models/
product.php
routes/
products.php
我的index.php 看起来像这样:
<?php
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../src/config/database.php';
// Instantiate the app
$settings = require __DIR__ . '/../src/config/settings.php';
$app = new \Slim\App(['settings' => $settings]);
// Set up handlers
$container = $app->getContainer();
require __DIR__ . "/../src/config/handlers.php";
// Register routes
require __DIR__ . '/../src/routes/products.php';
// Run app
$app->run();
我的handlers.php 文件包含所有自定义错误处理程序,如下所示:
<?php
/**
* Custom global error handler.
*/
$container['errorHandler'] = function($container) {
return function ($request, $response, $exception) use ($container) {
return $response->withStatus(500)
->withHeader('Content-Type', 'application/json')
->write(json_encode(array(
'error' => 'INTERNAL_ERROR',
'error_message' => 'Something went wrong internally.',
'status_code' => '500',
'trace' => $exception.getTraceAsString()
), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
};
};
/**
* Custom global PHP error handler.
*/
$container['phpErrorHandler'] = function($container) {
return $container['errorHandler'];
};
/**
* Custom 404 Not Found error handler.
*/
$container['notFoundHandler'] = function($container) {
return function ($request, $response) use ($container) {
return $response->withStatus(404)
->withHeader('Content-Type', 'application/json')
->write(json_encode(array(
'error' => 'NOT_FOUND',
'error_message' => 'Endpoint was not found. Check API documentation for valid endpoints.',
'status_code' => '404',
), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
};
};
/**
* Custom 405 Not Allowed error handler.
*/
$container['notAllowedHandler'] = function($container) {
return function ($request, $response, $methods) use ($container) {
return $response->withStatus(405)
->withHeader('Allow', implode(', ', $methods))
->withHeader('Content-Type', 'application/json')
->write(json_encode(array(
'error' => 'NOT_ALLOWED',
'error_message' => 'HTTP request method is not allowed. Method must be of: ' . implode(', ', $methods),
'status_code' => '405',
), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
};
};
到目前为止我所尝试的:
- 在创建
$app并将$container加载到其中之前添加所有处理程序。 - 在创建自定义处理程序之前取消设置现有处理程序,如下所示:
unset($app->getContainer()['notFoundHandler']);
我只是想不通出了什么问题,以及为什么在抛出错误时我仍然获得默认的 HTML 视图。
【问题讨论】:
-
您的代码(相关部分,没有数据库配置、路由等)对我有用。我怀疑你可能在 products.php 中做错了什么。尝试在不包含 products.php 的情况下运行您的代码,看看会发生什么。
-
@Nima,我浏览了 products.php 中的代码并注意到出了什么问题。我正在实例化一个新的
$app = new \Slim\App;。由于该文件中的所有路由都有效,我认为它与我的处理程序文件有关。为帮助干杯!