ErrorHandler.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace KarmaFW\App\Middlewares;
  3. use \KarmaFW\App;
  4. use \KarmaFW\Http\Request;
  5. use \KarmaFW\Http\Response;
  6. class ErrorHandler
  7. {
  8. protected $use_internal_handler;
  9. protected $use_whoops_handler;
  10. public function __construct($use_internal_handler=true, $use_whoops_handler=false)
  11. {
  12. $this->use_internal_handler = $use_internal_handler;
  13. $this->use_whoops_handler = $use_whoops_handler;
  14. }
  15. public function __invoke(Request $request, Response $response, callable $next)
  16. {
  17. //set_error_handler(['ErrorHandler', 'display']);
  18. //set_exception_handler(['ExceptionHandler', 'display']);
  19. if ($this->use_whoops_handler) {
  20. $whoops = new \Whoops\Run;
  21. $whoops->prependHandler(new \Whoops\Handler\PrettyPageHandler);
  22. $whoops->register();
  23. }
  24. try {
  25. $response = $next($request, $response);
  26. } catch (\Exception $e) {
  27. $error_code = $e->getCode();
  28. $error_message = $e->getMessage();
  29. // TODO: voir comment bien injecter cette dependance
  30. $debugbar = App::getData('debugbar');
  31. if ($debugbar) {
  32. if (isset($debugbar['exceptions'])) {
  33. $debugbar['exceptions']->addException($e);
  34. }
  35. }
  36. /*
  37. if ($error_code == 404) {
  38. // case moved to UrlRouter
  39. $response->setStatus(404)->html($error_message);
  40. }
  41. */
  42. if (! $this->use_internal_handler) {
  43. throw $e;
  44. }
  45. $http_code = (500 <= $error_code && $error_code <= 599) ? $error_code : 500;
  46. error_log("[UrlRouter] Error " . $error_code . " : " . $error_message);
  47. if (ENV == 'dev') {
  48. $title = "ErrorHandler CATCHED EXCEPTION CODE " . $error_code;
  49. $message = '<pre>' . print_r($e, true) . '</pre>';
  50. $response_content = '<title>' . $title . '</title><h1>' . $title . '</h1><h2>' . $error_message . '</h2><p>' . $message . '</p>';
  51. } else {
  52. $title = "Server Error";
  53. $message = 'An error has occured';
  54. $response_content = '<title>' . $title . '</title><h1>' . $title . '</h1><p>' . $message . '</p>';
  55. }
  56. if (App::isCli()) {
  57. echo $title . PHP_EOL . PHP_EOL;
  58. echo $message . PHP_EOL . PHP_EOL;
  59. exit;
  60. }
  61. $response->html($response_content, $http_code);
  62. }
  63. return $response;
  64. }
  65. }