我想覆盖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视图。
答案 0 :(得分:0)
由于@Nima,我发现自己意外地在$app = new \Slim\App;
文件中创建了products.php
的新实例。删除它即可正常工作。