CodeIgniter CI_Exceptions::show_exception error af

2020-04-08 13:56发布

问题:

I was using CodeIgniter 3.0.0 with PHP 5.6.

Yesterday I updated to PHP 7 and started getting following error:-

Uncaught TypeError: Argument 1 passed to CI_Exceptions::show_exception() must be
 an instance of Exception, instance of Error given, called in /my/file/path/app/system/core/Common.php on line 658 and defined in /my/file/path/hgx_portal/app/system/core/Exceptions.php:190
Stack trace:
#0 /my/file/path/hgx_portal/app/system/core/Common.php(658): CI_Exceptions->show_exception(Object
(Error))
#1 [internal function]: _exception_handler(Object(Error))
#2 {main}
  thrown in /my/file/path/hgx_portal/app/system/core/Exceptions.phpon line 190

回答1:

This is a know issue in CodeIgniter 3.0.0, see the github issue here and changelog below:

Fixed a bug (#4137) - :doc:Error Handling <general/errors> breaks for the new Error exceptions under PHP 7.

It's because set_exception_handler() changed behavior in PHP 7.

Code that implements an exception handler registered with set_exception_handler() using a type declaration of Exception will cause a fatal error when an Error object is thrown.

If the handler needs to work on both PHP 5 and 7, you should remove the type declaration from the handler, while code that is being migrated to work on PHP 7 exclusively can simply replace the Exception type declaration with Throwable instead.

<?php
// PHP 5 era code that will break.
function handler(Exception $e) { ... }
set_exception_handler('handler');

// PHP 5 and 7 compatible.
function handler($e) { ... }

// PHP 7 only.
function handler(Throwable $e) { ... }
?>

Upgrading to anything beyond 3.0.2 will fix your issue.



回答2:

This error is caused by PHP 7 (which throws Error instead Exception in set_exception_handler function.

If you cannot do an upgrade the CodeIgniter system folder, you can just change the file system/core/Exceptions.php at line 190:

public function show_exception(Exception $exception)

To

public function show_exception($exception)