Application

The Application Slim\App is the entry point to your Slim application and is used to register the routes that link to your callbacks or controllers.

  1. <?php
  2. use Psr\Http\Message\ResponseInterface as Response;
  3. use Psr\Http\Message\ServerRequestInterface as Request;
  4. use Slim\Factory\AppFactory;
  5. require __DIR__ . '/../vendor/autoload.php';
  6. // Instantiate app
  7. $app = AppFactory::create();
  8. // Add Error Handling Middleware
  9. $app->addErrorMiddleware(true, false, false);
  10. // Add route callbacks
  11. $app->get('/', function (Request $request, Response $response, array $args) {
  12. $response->getBody()->write('Hello World');
  13. return $response;
  14. });
  15. // Run application
  16. $app->run();

Advanced Notices and Warnings Handling

Warnings and Notices are not caught by default. If you wish your application to display an error page when they happen, you will need to implement code similar to the following index.php.

  1. <?php
  2. use MyApp\Handlers\ErrorHandler;
  3. use MyApp\Handlers\ShutdownHandler;
  4. use Slim\Exception\HttpInternalServerErrorException;
  5. use Slim\Factory\AppFactory;
  6. use Slim\Factory\ServerRequestCreatorFactory;
  7. require __DIR__ . '/../vendor/autoload.php';
  8. // Set that to your needs
  9. $displayErrorDetails = true;
  10. $app = AppFactory::create();
  11. $callableResolver = $app->getCallableResolver();
  12. $responseFactory = $app->getResponseFactory();
  13. $serverRequestCreator = ServerRequestCreatorFactory::create();
  14. $request = $serverRequestCreator->createFromGlobals();
  15. $errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);
  16. $shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
  17. register_shutdown_function($shutdownHandler);
  18. // Add Routing Middleware
  19. $app->addRoutingMiddleware();
  20. // Add Error Handling Middleware
  21. $errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
  22. $errorMiddleware->setDefaultErrorHandler($errorHandler);
  23. $app->run();

Advanced Custom Error Handler

  1. <?php
  2. namespace MyApp\Handlers;
  3. use Psr\Http\Message\ResponseInterface;
  4. use Slim\Exception\HttpBadRequestException;
  5. use Slim\Exception\HttpException;
  6. use Slim\Exception\HttpForbiddenException;
  7. use Slim\Exception\HttpMethodNotAllowedException;
  8. use Slim\Exception\HttpNotFoundException;
  9. use Slim\Exception\HttpNotImplementedException;
  10. use Slim\Exception\HttpUnauthorizedException;
  11. use Slim\Handlers\ErrorHandler;
  12. use Exception;
  13. use Throwable;
  14. class HttpErrorHandler extends ErrorHandler
  15. {
  16. public const BAD_REQUEST = 'BAD_REQUEST';
  17. public const INSUFFICIENT_PRIVILEGES = 'INSUFFICIENT_PRIVILEGES';
  18. public const NOT_ALLOWED = 'NOT_ALLOWED';
  19. public const NOT_IMPLEMENTED = 'NOT_IMPLEMENTED';
  20. public const RESOURCE_NOT_FOUND = 'RESOURCE_NOT_FOUND';
  21. public const SERVER_ERROR = 'SERVER_ERROR';
  22. public const UNAUTHENTICATED = 'UNAUTHENTICATED';
  23. protected function respond(): ResponseInterface
  24. {
  25. $exception = $this->exception;
  26. $statusCode = 500;
  27. $type = self::SERVER_ERROR;
  28. $description = 'An internal error has occurred while processing your request.';
  29. if ($exception instanceof HttpException) {
  30. $statusCode = $exception->getCode();
  31. $description = $exception->getMessage();
  32. if ($exception instanceof HttpNotFoundException) {
  33. $type = self::RESOURCE_NOT_FOUND;
  34. } elseif ($exception instanceof HttpMethodNotAllowedException) {
  35. $type = self::NOT_ALLOWED;
  36. } elseif ($exception instanceof HttpUnauthorizedException) {
  37. $type = self::UNAUTHENTICATED;
  38. } elseif ($exception instanceof HttpForbiddenException) {
  39. $type = self::UNAUTHENTICATED;
  40. } elseif ($exception instanceof HttpBadRequestException) {
  41. $type = self::BAD_REQUEST;
  42. } elseif ($exception instanceof HttpNotImplementedException) {
  43. $type = self::NOT_IMPLEMENTED;
  44. }
  45. }
  46. if (
  47. !($exception instanceof HttpException)
  48. && ($exception instanceof Exception || $exception instanceof Throwable)
  49. && $this->displayErrorDetails
  50. ) {
  51. $description = $exception->getMessage();
  52. }
  53. $error = [
  54. 'statusCode' => $statusCode,
  55. 'error' => [
  56. 'type' => $type,
  57. 'description' => $description,
  58. ],
  59. ];
  60. $payload = json_encode($error, JSON_PRETTY_PRINT);
  61. $response = $this->responseFactory->createResponse($statusCode);
  62. $response->getBody()->write($payload);
  63. return $response;
  64. }
  65. }

Advanced Shutdown Handler

  1. <?php
  2. namespace MyApp\Handlers;
  3. use MyApp\Handlers\HttpErrorHandler;
  4. use Psr\Http\Message\ServerRequestInterface;
  5. use Slim\Exception\HttpInternalServerErrorException;
  6. use Slim\ResponseEmitter;
  7. class ShutdownHandler
  8. {
  9. /**
  10. * @var Request
  11. */
  12. private $request;
  13. /**
  14. * @var HttpErrorHandler
  15. */
  16. private $errorHandler;
  17. /**
  18. * @var bool
  19. */
  20. private $displayErrorDetails;
  21. /**
  22. * ShutdownHandler constructor.
  23. *
  24. * @param Request $request
  25. * @param HttpErrorHandler $errorHandler
  26. * @param bool $displayErrorDetails
  27. */
  28. public function __construct(Request $request, HttpErrorHandler $errorHandler, bool $displayErrorDetails) {
  29. $this->request = $request;
  30. $this->errorHandler = $errorHandler;
  31. $this->displayErrorDetails = $displayErrorDetails;
  32. }
  33. public function __invoke()
  34. {
  35. $error = error_get_last();
  36. if ($error) {
  37. $errorFile = $error['file'];
  38. $errorLine = $error['line'];
  39. $errorMessage = $error['message'];
  40. $errorType = $error['type'];
  41. $message = 'An error while processing your request. Please try again later.';
  42. if ($this->displayErrorDetails) {
  43. switch ($errorType) {
  44. case E_USER_ERROR:
  45. $message = "FATAL ERROR: {$errorMessage}. ";
  46. $message .= " on line {$errorLine} in file {$errorFile}.";
  47. break;
  48. case E_USER_WARNING:
  49. $message = "WARNING: {$errorMessage}";
  50. break;
  51. case E_USER_NOTICE:
  52. $message = "NOTICE: {$errorMessage}";
  53. break;
  54. default:
  55. $message = "ERROR: {$errorMessage}";
  56. $message .= " on line {$errorLine} in file {$errorFile}.";
  57. break;
  58. }
  59. }
  60. $exception = new HttpInternalServerErrorException($this->request, $message);
  61. $response = $this->errorHandler->__invoke($this->request, $exception, $this->displayErrorDetails, false, false);
  62. ob_clean();
  63. $responseEmitter = new ResponseEmitter();
  64. $responseEmitter->emit($response);
  65. }
  66. }
  67. }