Обработка ошибок(Error Handling)
В случае возникновения неустранимой ошибки в вашем приложении, в большинстве случаев нужно прекратить выполнение скрипта и показать сообщение об ошибке. Чтобы избавить вас от обработки каждого исключения в вашем контроллере или компоненте, в CakePHP есть метод:
Простой текст$this->cakeError(<string errorType>, [массив параметров]);
При вызове этого метода пользователь увидит страницу ошибки и все дальнейшие скрипты вашего приложения прекратят выполнение.
В CakePHP предопределен ряд типов ошибок, которые также использовались в процессе создания самого CakePHP. Один из них это старый добрый 404 error. Чтобы показать эту страницу вам достаточно сделать следующее:
Простой текст$this->cakeError('error404');
Or alternatively, you can cause the page to report the error was at a specific URL by passing the url parameter:
$this->cakeError('error404', array('url' => 'some/other.url'));
This all starts being a lot more useful by extending the error handler to use your own custom error-types. Custom error handlers are largely like controller actions. You typically will set() any passed parameters to be available to the view and then render a view file from your app/views/errors
directory.
Create a file app/app_error.php with the following definition.
Простой текст
<?phpclass AppError extends ErrorHandler {}?>
Handlers for new error-types can be implemented by adding methods to this class. Simply create a new method with the name you want to use as your error-type.
Let's say we have an application that writes a number of files to disk and that it is appropriate to report write errors to the user. We don't want to add code for this all over the different parts of our application, so this is a great case for using a new error type.
Add a new method to your AppError class. We'll take one parameter called file that will be the path to the file we failed to write.
function cannotWriteFile($params) {$this->controller->set('file', $params['file']);$this->_outputMessage('cannot_write_file');}
Create the view in app/views/errors/cannot_write_file.ctp
<h2>Unable to write file</h2><p>Could not write file <?php echo $file ?> to the disk.</p>
and throw the error in your controller/component
Простой текст$this->cakeError('cannotWriteFile', array('file'=>'somefilename'));
The default implementation of $this->__outputMessage(<view-filename>) will just display the view in views/errors/<view-filename>.ctp. If you wish to override this behaviour, you can redefine __outputMessage($template) in your AppError class.


Коментарии:
Добавить коментарий