Adding ErrorHandler::handleError for consolidating core error handling out of CakeLog and Debugger.

This commit is contained in:
mark_story 2010-11-14 20:00:27 -05:00
parent 6d5cf96d1c
commit da3bf1c747
2 changed files with 68 additions and 0 deletions

View file

@ -178,6 +178,29 @@ class ErrorHandler {
$error->render();
}
/**
* Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
* error handling methods. This function will use Debugger to display errors when debug > 0. And
* will log errors to CakeLog, when debug == 0.
*
* You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
*
* @param integer $code Code of error
* @param string $description Error description
* @param string $file File on which error occurred
* @param integer $line Line that triggered the error
* @param array $context Context
* @return boolean true if error was handled
*/
public static function handleError($code, $description, $file = null, $line = null, $context = null) {
$debug = Configure::read('debug');
if ($debug) {
return Debugger::handleError($code, $description, $file, $line, $context);
} else {
return CakeLog::handleError($code, $description, $file, $line, $context);
}
}
/**
* Renders the response for the exception.
*

View file

@ -151,6 +151,7 @@ class MissingWidgetThingException extends NotFoundException { }
*/
class ErrorHandlerTest extends CakeTestCase {
var $_restoreError = false;
/**
* setup create a request object to get out of router later.
*
@ -179,6 +180,9 @@ class ErrorHandlerTest extends CakeTestCase {
function teardown() {
Configure::write('debug', $this->_debug);
App::build();
if ($this->_restoreError) {
restore_error_handler();
}
}
/**
@ -191,6 +195,47 @@ class ErrorHandlerTest extends CakeTestCase {
return $error;
}
/**
* test error handling when debug is on, an error should be printed from Debugger.
*
* @return void
*/
function testHandleErrorDebugOn() {
set_error_handler('ErrorHandler::handleError');
$this->_restoreError = true;
ob_start();
$wrong .= '';
$result = ob_get_clean();
$this->assertPattern('/<pre class="cake-debug">/', $result);
$this->assertPattern('/<b>Notice<\/b>/', $result);
$this->assertPattern('/variable:\s+wrong/', $result);
}
/**
* Test that errors go into CakeLog when debug = 0.
*
* @return void
*/
function testHandleErrorDebugOff() {
Configure::write('debug', 0);
@unlink(LOGS . 'debug.log');
set_error_handler('ErrorHandler::handleError');
$this->_restoreError = true;
$out .= '';
$result = file(LOGS . 'debug.log');
$this->assertEqual(count($result), 1);
$this->assertPattern(
'/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} Notice: Notice \(8\): Undefined variable:\s+out in \[.+ line \d+\]$/',
$result[0]
);
@unlink(LOGS . 'debug.log');
}
/**
* test handleException generating a page.
*