Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16591 anikendra 1
<?php
2
/**
3
 * ErrorHandler class
4
 *
5
 * Provides Error Capturing for Framework errors.
6
 *
7
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
8
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
9
 *
10
 * Licensed under The MIT License
11
 * For full copyright and license information, please see the LICENSE.txt
12
 * Redistributions of files must retain the above copyright notice.
13
 *
14
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
15
 * @link          http://cakephp.org CakePHP(tm) Project
16
 * @package       Cake.Error
17
 * @since         CakePHP(tm) v 0.10.5.1732
18
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
19
 */
20
 
21
App::uses('Debugger', 'Utility');
22
App::uses('CakeLog', 'Log');
23
App::uses('ExceptionRenderer', 'Error');
24
App::uses('Router', 'Routing');
25
 
26
/**
27
 * Error Handler provides basic error and exception handling for your application. It captures and
28
 * handles all unhandled exceptions and errors. Displays helpful framework errors when debug > 1.
29
 *
30
 * ### Uncaught exceptions
31
 *
32
 * When debug < 1 a CakeException will render 404 or 500 errors. If an uncaught exception is thrown
33
 * and it is a type that ErrorHandler does not know about it will be treated as a 500 error.
34
 *
35
 * ### Implementing application specific exception handling
36
 *
37
 * You can implement application specific exception handling in one of a few ways. Each approach
38
 * gives you different amounts of control over the exception handling process.
39
 *
40
 * - Set Configure::write('Exception.handler', 'YourClass::yourMethod');
41
 * - Create AppController::appError();
42
 * - Set Configure::write('Exception.renderer', 'YourClass');
43
 *
44
 * #### Create your own Exception handler with `Exception.handler`
45
 *
46
 * This gives you full control over the exception handling process. The class you choose should be
47
 * loaded in your app/Config/bootstrap.php, so its available to handle any exceptions. You can
48
 * define the handler as any callback type. Using Exception.handler overrides all other exception
49
 * handling settings and logic.
50
 *
51
 * #### Using `AppController::appError();`
52
 *
53
 * This controller method is called instead of the default exception rendering. It receives the
54
 * thrown exception as its only argument. You should implement your error handling in that method.
55
 * Using AppController::appError(), will supersede any configuration for Exception.renderer.
56
 *
57
 * #### Using a custom renderer with `Exception.renderer`
58
 *
59
 * If you don't want to take control of the exception handling, but want to change how exceptions are
60
 * rendered you can use `Exception.renderer` to choose a class to render exception pages. By default
61
 * `ExceptionRenderer` is used. Your custom exception renderer class should be placed in app/Lib/Error.
62
 *
63
 * Your custom renderer should expect an exception in its constructor, and implement a render method.
64
 * Failing to do so will cause additional errors.
65
 *
66
 * #### Logging exceptions
67
 *
68
 * Using the built-in exception handling, you can log all the exceptions
69
 * that are dealt with by ErrorHandler by setting `Exception.log` to true in your core.php.
70
 * Enabling this will log every exception to CakeLog and the configured loggers.
71
 *
72
 * ### PHP errors
73
 *
74
 * Error handler also provides the built in features for handling php errors (trigger_error).
75
 * While in debug mode, errors will be output to the screen using debugger. While in production mode,
76
 * errors will be logged to CakeLog. You can control which errors are logged by setting
77
 * `Error.level` in your core.php.
78
 *
79
 * #### Logging errors
80
 *
81
 * When ErrorHandler is used for handling errors, you can enable error logging by setting `Error.log` to true.
82
 * This will log all errors to the configured log handlers.
83
 *
84
 * #### Controlling what errors are logged/displayed
85
 *
86
 * You can control which errors are logged / displayed by ErrorHandler by setting `Error.level`. Setting this
87
 * to one or a combination of a few of the E_* constants will only enable the specified errors.
88
 *
89
 * e.g. `Configure::write('Error.level', E_ALL & ~E_NOTICE);`
90
 *
91
 * Would enable handling for all non Notice errors.
92
 *
93
 * @package       Cake.Error
94
 * @see ExceptionRenderer for more information on how to customize exception rendering.
95
 */
96
class ErrorHandler {
97
 
98
/**
99
 * Whether to give up rendering an exception, if the renderer itself is
100
 * throwing exceptions.
101
 *
102
 * @var bool
103
 */
104
	protected static $_bailExceptionRendering = false;
105
 
106
/**
107
 * Set as the default exception handler by the CakePHP bootstrap process.
108
 *
109
 * This will either use custom exception renderer class if configured,
110
 * or use the default ExceptionRenderer.
111
 *
112
 * @param Exception $exception The exception to render.
113
 * @return void
114
 * @see http://php.net/manual/en/function.set-exception-handler.php
115
 */
116
	public static function handleException(Exception $exception) {
117
		$config = Configure::read('Exception');
118
		static::_log($exception, $config);
119
 
120
		$renderer = isset($config['renderer']) ? $config['renderer'] : 'ExceptionRenderer';
121
		if ($renderer !== 'ExceptionRenderer') {
122
			list($plugin, $renderer) = pluginSplit($renderer, true);
123
			App::uses($renderer, $plugin . 'Error');
124
		}
125
		try {
126
			$error = new $renderer($exception);
127
			$error->render();
128
		} catch (Exception $e) {
129
			set_error_handler(Configure::read('Error.handler')); // Should be using configured ErrorHandler
130
			Configure::write('Error.trace', false); // trace is useless here since it's internal
131
			$message = sprintf("[%s] %s\n%s", // Keeping same message format
132
				get_class($e),
133
				$e->getMessage(),
134
				$e->getTraceAsString()
135
			);
136
 
137
			static::$_bailExceptionRendering = true;
138
			trigger_error($message, E_USER_ERROR);
139
		}
140
	}
141
 
142
/**
143
 * Generates a formatted error message
144
 *
145
 * @param Exception $exception Exception instance
146
 * @return string Formatted message
147
 */
148
	protected static function _getMessage($exception) {
149
		$message = sprintf("[%s] %s",
150
			get_class($exception),
151
			$exception->getMessage()
152
		);
153
		if (method_exists($exception, 'getAttributes')) {
154
			$attributes = $exception->getAttributes();
155
			if ($attributes) {
156
				$message .= "\nException Attributes: " . var_export($exception->getAttributes(), true);
157
			}
158
		}
159
		if (PHP_SAPI !== 'cli') {
160
			$request = Router::getRequest();
161
			if ($request) {
162
				$message .= "\nRequest URL: " . $request->here();
163
			}
164
		}
165
		$message .= "\nStack Trace:\n" . $exception->getTraceAsString();
166
		return $message;
167
	}
168
 
169
/**
170
 * Handles exception logging
171
 *
172
 * @param Exception $exception The exception to render.
173
 * @param array $config An array of configuration for logging.
174
 * @return bool
175
 */
176
	protected static function _log(Exception $exception, $config) {
177
		if (empty($config['log'])) {
178
			return false;
179
		}
180
 
181
		if (!empty($config['skipLog'])) {
182
			foreach ((array)$config['skipLog'] as $class) {
183
				if ($exception instanceof $class) {
184
					return false;
185
				}
186
			}
187
		}
188
		return CakeLog::write(LOG_ERR, static::_getMessage($exception));
189
	}
190
 
191
/**
192
 * Set as the default error handler by CakePHP. Use Configure::write('Error.handler', $callback), to use your own
193
 * error handling methods. This function will use Debugger to display errors when debug > 0. And
194
 * will log errors to CakeLog, when debug == 0.
195
 *
196
 * You can use Configure::write('Error.level', $value); to set what type of errors will be handled here.
197
 * Stack traces for errors can be enabled with Configure::write('Error.trace', true);
198
 *
199
 * @param int $code Code of error
200
 * @param string $description Error description
201
 * @param string $file File on which error occurred
202
 * @param int $line Line that triggered the error
203
 * @param array $context Context
204
 * @return bool true if error was handled
205
 */
206
	public static function handleError($code, $description, $file = null, $line = null, $context = null) {
207
		if (error_reporting() === 0) {
208
			return false;
209
		}
210
		$errorConfig = Configure::read('Error');
211
		list($error, $log) = static::mapErrorCode($code);
212
		if ($log === LOG_ERR) {
213
			return static::handleFatalError($code, $description, $file, $line);
214
		}
215
 
216
		$debug = Configure::read('debug');
217
		if ($debug) {
218
			$data = array(
219
				'level' => $log,
220
				'code' => $code,
221
				'error' => $error,
222
				'description' => $description,
223
				'file' => $file,
224
				'line' => $line,
225
				'context' => $context,
226
				'start' => 2,
227
				'path' => Debugger::trimPath($file)
228
			);
229
			return Debugger::getInstance()->outputError($data);
230
		}
231
		$message = $error . ' (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
232
		if (!empty($errorConfig['trace'])) {
233
			$trace = Debugger::trace(array('start' => 1, 'format' => 'log'));
234
			$message .= "\nTrace:\n" . $trace . "\n";
235
		}
236
		return CakeLog::write($log, $message);
237
	}
238
 
239
/**
240
 * Generate an error page when some fatal error happens.
241
 *
242
 * @param int $code Code of error
243
 * @param string $description Error description
244
 * @param string $file File on which error occurred
245
 * @param int $line Line that triggered the error
246
 * @return bool
247
 * @throws FatalErrorException If the Exception renderer threw an exception during rendering, and debug > 0.
248
 * @throws InternalErrorException If the Exception renderer threw an exception during rendering, and debug is 0.
249
 */
250
	public static function handleFatalError($code, $description, $file, $line) {
251
		$logMessage = 'Fatal Error (' . $code . '): ' . $description . ' in [' . $file . ', line ' . $line . ']';
252
		CakeLog::write(LOG_ERR, $logMessage);
253
 
254
		$exceptionHandler = Configure::read('Exception.handler');
255
		if (!is_callable($exceptionHandler)) {
256
			return false;
257
		}
258
 
259
		if (ob_get_level()) {
260
			ob_end_clean();
261
		}
262
 
263
		if (Configure::read('debug')) {
264
			$exception = new FatalErrorException($description, 500, $file, $line);
265
		} else {
266
			$exception = new InternalErrorException();
267
		}
268
 
269
		if (static::$_bailExceptionRendering) {
270
			static::$_bailExceptionRendering = false;
271
			throw $exception;
272
		}
273
 
274
		call_user_func($exceptionHandler, $exception);
275
 
276
		return false;
277
	}
278
 
279
/**
280
 * Map an error code into an Error word, and log location.
281
 *
282
 * @param int $code Error code to map
283
 * @return array Array of error word, and log location.
284
 */
285
	public static function mapErrorCode($code) {
286
		$error = $log = null;
287
		switch ($code) {
288
			case E_PARSE:
289
			case E_ERROR:
290
			case E_CORE_ERROR:
291
			case E_COMPILE_ERROR:
292
			case E_USER_ERROR:
293
				$error = 'Fatal Error';
294
				$log = LOG_ERR;
295
				break;
296
			case E_WARNING:
297
			case E_USER_WARNING:
298
			case E_COMPILE_WARNING:
299
			case E_RECOVERABLE_ERROR:
300
				$error = 'Warning';
301
				$log = LOG_WARNING;
302
				break;
303
			case E_NOTICE:
304
			case E_USER_NOTICE:
305
				$error = 'Notice';
306
				$log = LOG_NOTICE;
307
				break;
308
			case E_STRICT:
309
				$error = 'Strict';
310
				$log = LOG_NOTICE;
311
				break;
312
			case E_DEPRECATED:
313
			case E_USER_DEPRECATED:
314
				$error = 'Deprecated';
315
				$log = LOG_NOTICE;
316
				break;
317
		}
318
		return array($error, $log);
319
	}
320
 
321
}