Просмотр файла app/Handlers/HttpErrorHandler.php

Размер файла: 1.88Kb
  1. <?php
  2.  
  3. declare(strict_types=1);
  4.  
  5. namespace App\Handlers;
  6.  
  7. use App\Services\View;
  8. use Psr\Http\Message\ResponseInterface as Response;
  9. use Slim\Exception\HttpException;
  10. use Slim\Handlers\ErrorHandler as SlimErrorHandler;
  11. use Whoops\Handler\JsonResponseHandler;
  12. use Whoops\Handler\PrettyPageHandler;
  13. use Whoops\Run;
  14. use Whoops\Util\Misc;
  15.  
  16. class HttpErrorHandler extends SlimErrorHandler
  17. {
  18. /**
  19. * @inheritdoc
  20. */
  21. protected function respond(): Response
  22. {
  23. $response = $this->responseFactory->createResponse();
  24.  
  25. if ($this->exception instanceof HttpException || ! setting('debug')) {
  26. $code = $this->statusCode;
  27.  
  28. if (strtolower($this->request->getHeaderLine('X-Requested-With')) === 'xmlhttprequest') {
  29. $error = [
  30. 'error' => [
  31. 'code' => $code,
  32. 'message' => $this->exception->getMessage(),
  33. ]
  34. ];
  35. $response->getBody()->write((string) json_encode($error));
  36.  
  37. return $response->withStatus($code)->withHeader('Content-Type', 'application/json');
  38. }
  39.  
  40. if (! app(View::class)->exists('errors/' . $code)) {
  41. $code = 500;
  42. }
  43.  
  44. $response = app(View::class)->render(
  45. $response,
  46. 'errors/' . $code,
  47. ['message' => $this->exception->getMessage()]
  48. );
  49.  
  50. return $response->withStatus($code);
  51. }
  52.  
  53. if (class_exists(Run::class) && setting('debug')) {
  54. $handler = Misc::isAjaxRequest() ?
  55. new JsonResponseHandler() :
  56. new PrettyPageHandler();
  57.  
  58. $whoops = new Run();
  59. $whoops->pushHandler($handler);
  60.  
  61. $response->getBody()->write($whoops->handleException($this->exception));
  62. }
  63.  
  64. return $response;
  65. }
  66. }