dou426098 2019-03-30 12:03
浏览 59

Slim 3中的自定义错误处理程序无法正常工作

I want to override the default error handlers in Slim 3 and respond with JSON instead of the default HTML page. But I can't get it to work, my custom handlers are ignored completely and I can't figure out why.

My project structure looks like this:

api/
  public/
    index.php
  src/
    config/
      database.php
      handlers.php
      settings.php
    models/
      product.php
    routes/
      products.php

My index.php looks like this:

<?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();

And my handlers.php file with all the custom error handlers looks like this:

<?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));    
  };
};

What I have tried so far:

  • Adding all handlers before creating $app and loading the $container into it.
  • Unset the existing handler before creating a custom one, like so: unset($app->getContainer()['notFoundHandler']);

I just can't wrap my head around what goes wrong and why I am still getting the default HTML views when an error is thrown.

  • 写回答

1条回答 默认 最新

  • dougan6982 2019-03-30 13:09
    关注

    Thanks to @Nima I figured out that I had accidentally created a new instance of the $app = new \Slim\App; inside my products.php file. Removing that got it to work.

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比