Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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