php: autoload exception handling - php

I'm extending my previous question (Handling exceptions within exception handle) to address my bad coding practice.
I'm trying to delegate autoload errors to a exception handler.
<?php
function __autoload($class_name) {
$file = $class_name.'.php';
try {
if (file_exists($file)) {
include $file;
}else{
throw new loadException("File $file is missing");
}
if(!class_exists($class_name,false)){
throw new loadException("Class $class_name missing in $file");
}
}catch(loadException $e){
header("HTTP/1.0 500 Internal Server Error");
$e->loadErrorPage('500');
exit;
}
return true;
}
class loadException extends Exception {
public function __toString()
{
return get_class($this) . " in {$this->file}({$this->line})".PHP_EOL
."'{$this->message}'".PHP_EOL
. "{$this->getTraceAsString()}";
}
public function loadErrorPage($code){
try {
$page = new pageClass();
echo $page->showPage($code);
}catch(Exception $e){
echo 'fatal error: ', $code;
}
}
}
$test = new testClass();
?>
the above script is supposed to load a 404 page if the testClass.php file is missing, and it works fine, UNLESS the pageClass.php file is missing as well, in which case I see a
"Fatal error: Class 'pageClass' not found in D:\xampp\htdocs\Test\PHP\errorhandle\index.php on line 29" instead of the "fatal error: 500" message
I do not want to add a try/catch block to each and every class autoload (object creation), so i tried this.
What is the proper way of handling this?

Have you tried checking for pageClass early on in the process, since it seems to be necessary even to get the error page out? If it doesn't exist, and if you don't want to write the 404 page w/o any objects (e.g. just HTML), bombing out of execution where that class doesn't exist would seem to be a good path.
Hope that helps.
Thanks,
Joe

Related

Zend Exception instead of 404

My ZF app is throwing an exception instead of returning a 404 for urls which are really 404s. E.g. testlotto.ie/rrr should be a 404, yet I get the following:
Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' with message 'Invalid controller specified (rrr)' in /mnt/pc/sites/git-lotto/lotto/irish-lotto/library/Zend/Controller/Dispatcher/Standard.php:
I have tried the suggestions on Fatal error: Uncaught exception 'Zend_Controller_Dispatcher_Exception' while creating object of model class and Uncaught exception 'Zend_Controller_Dispatcher_Exception' (as well as many others), and nothing is working.
I do have my ErrorController controller in the ../application/controllers dir, which is what is returned when I die() out getControllerDirectory() from Controller/Dispatcher/Standard.php - so no problem of controller not being found.
My ErrorController is as follows (not that it matters as it is not getting called):
<?php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$this->getResponse()->setRawHeader('HTTP/1.1 404 Not Found');
$content =<<<EOH
<h1>Unlucky!</h1>
<p>The url you entered is not a valid one - please check what you typed, the mistake is most likely there.</p>
EOH;
break;
default:
// application error
$content =<<<EOH
<h1>Error!</h1>
<p>An unexpected error occurred. Please try again later.</p>
EOH;
break;
}
// Clear previous content
$this->getResponse()->clearBody();
$this->view->content = $content;
}
}
The start of the despatch method is:
public function dispatch(Zend_Controller_Request_Abstract $request, Zend_Controller_Response_Abstract $response)
{
$this->setResponse($response);
/**
* Get controller class
*/
if (!$this->isDispatchable($request)) {
$controller = $request->getControllerName();
//die($controller);
//$this->setParam('useDefaultControllerAlways',true);
//ErrorController::errorAction();
if (!$this->getParam('useDefaultControllerAlways') && !empty($controller)) {
require_once 'Zend/Controller/Dispatcher/Exception.php';
throw new Zend_Controller_Dispatcher_Exception('Invalid controller specified (' . $request->getControllerName() . ')');
}
$className = $this->getDefaultControllerClass($request);
As you can see, I tried as suggested setting setParam('useDefaultControllerAlways',true);, but all this achieves is the homepage of the website is rendered (default controller of course) with a 200 response code - I need a 404.
Also, $controller dies out as the "rrr" in this example.
My question is what do I need to do to get 404's returned? This used to work on my site - I just swapped servers and now it is not working.
The only solution I could find to this which worked (i.e. the site now correctly returns a 404 for urls which do not exist), was taken from http://www.christopherhogan.com/2012/06/13/zend-framework-404-page/
Specifically, adding the below to my bootstrap file does the trick:
try {
$frontController->dispatch(); //instead of just $frontController->dispatch();
} catch (Zend_Exception $e) {
// this is where the 404 goes
header( 'HTTP/1.0 404 Not Found' );
echo "<div style='float:center; width:1000px; margin:0 auto;'><img src='http://www.foundco.com/images/404.jpg' alt='Everything is gonna be fine, please do not panic!' /></div>";
}
However, it's not perfect, as my ErrorController does not get called into action. If anyone could suggest how to trigger my ErrorController from the bootstrap file, would be much appreciated.

How can I check if file exists with exception handeling

I am trying to use exception handling in case a file does not exists. For example when I run the model method and pass a string usr (which I know there is no file with that name) . It gives me the following error message
Fatal error: Uncaught exception 'Exception' with message 'Usr.php was not found' in /app/core/controller.php on line 14
I can't figure out whats wrong here. Can someone please help me figure this out?
Below is my code. Thanks alot!
class Controllers{
public function model($model){
if(!file_exists("../app/models/".$model.".php")) {
throw new exception("{$model}.php was not found");
}
try {
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
You can't throw an exception without catching it; this automatically causes the PHP script to crash. So, you need to surround your entire function in the try-catch block, or the "model not found" exception will be uncaught. Your code should be something like this:
<?php
class Controllers {
public function model($model){
try {
if (!file_exists("../app/models/".$model.".php")) {
throw new Exception("{$model}.php was not found");
}
require ("../app/models/".$model.".php");
} catch(Exception $e) {
echo $e->getMessage();
}
return new $model();
}
}
Never mind guys! I found out I needed to use the try/catch blocks in the file where my method is being invoked
Example..
class Home extends Controllers{
public function index($name = ""){
try{
$user = $this->model('Usr');
}catch (Exception $e){
echo $e->getMessage();
}
//var_dump($user);
}

How to catch an exception from another class method PHP

I'm having trouble catching an exception in PHP
Here's my code.
try {
require $this->get_file_name($action);
}
catch (Exception $e) {
//do something//
}
and the method being called
private function get_file_name($action) {
$file = '../private/actions/actions_'.$this->group.'.php';
if (file_exists($file) === false) {
throw new Exception('The file for this '.$action.' was not found.');
}
else {
return $file;
}
}
Resulting in:
Fatal error: Uncaught exception 'Exception' with message $action was not found.'
Exception: The file for this $action was not found.
However If I put a try-catch block inside of the function and call the function, I'm able to catch the exception no problem.
What am I doing wrong?
If you are catching the Exception inside a namespace, make sure that you fall back to the global namespace:
...
}(catch \Exception $e) {
...
}...
You can also have a look at the following resources:
Why isn't my Exception being caught by catch?
http://php.net/manual/en/language.exceptions.php, top note by user zmunoz
I can't see all of the class body but If You want to use method out of the class it should be Public not Private.
Try to check if file You trying to get exists:
var_dump($file = '../private/actions/actions_'.$this->group.'.php');
IMO there is no file in this path

I'm trying to handle an Exception in PHP but stack error is still showing rather than being handled by catch

I'm calling a method that I know could cause an error and I'm trying to handle the error by wrapping the code in a try/catch statement...
class TestController extends Zend_Controller_Action
{
public function init()
{
// Anything here happens BEFORE the View has rendered
}
public function indexAction()
{
// Anything `echo`ed here is added to the end of the View
$model = new Application_Model_Testing('Mark', 31);
$this->view->sentence = $model->test();
$this->loadDataWhichCouldCauseError();
$this->loadView($model); // this method 'forwards' the Action onto another Controller
}
private function loadDataWhichCouldCauseError()
{
try {
$test = new Application_Model_NonExistent();
} catch (Exception $e) {
echo 'Handle the error';
}
}
private function loadView($model)
{
// Let's pretend we have loads of Models that require different Views
switch (get_class($model)) {
case 'Application_Model_Testing':
// Controller's have a `_forward` method to pass the Action onto another Controller
// The following line forwards to an `indexAction` within the `BlahController`
// It also passes some data onto the `BlahController`
$this->_forward('index', 'blah', null, array('data' => 'some data'));
break;
}
}
}
...but the problem I have is that the error isn't being handled. When viewing the application I get the following error...
( ! ) Fatal error: Class 'Application_Model_NonExistent' not found in /Library/WebServer/Documents/ZendTest/application/controllers/TestController.php on line 23
Can any one explain why this is happening and how I can get it to work?
Thanks
use
if (class_exists('Application_Model_NonExistent')) {
$test = new Application_Model_NonExistent;
} else {
echo 'class not found.';
}
like #prodigitalson said you can't catch that fatal error.
An error and an exception are not the same thing. Exceptions are thrown and meant to be caught, where errors are generally unrecoverable and triggered with http://www.php.net/manual/en/function.trigger-error.php
PHP: exceptions vs errors?
Can I try/catch a warning?
If you need to do some cleanup because of an error, you can use http://www.php.net/manual/en/function.set-error-handler.php
Thats not an exception, thats a FATAL error meaning you cant catch it like that. By definition a FATAL should not be recoverable.
Exception and Error are different things. There is an Exception class, which you are using and that $e is it's object.
You want to handle errors, check error handling in php-zend framework. But here, this is a Fatal error, you must rectify it, can not be handled.

phpUnit - mock php extended exception object

I'm testing some legacy code that extends the default php exception object. This code prints out a custom HTML error message.
I would like to mock this exception object in such a way that when the tested code generates an exception it will just echo the basic message instead of giving me the whole HTML message.
I cannot figure out a way to do this. It seems like you can test for explicit exceptions, but you can't change in a general way the behavior of an exception, and you also can't mock up an object that extends a default php functionality. ( can't think of another example of this beyond exceptions... but it would seem to be the case )
I guess the problem is, where would you attach the mocked object?? It seems like you can't interfere with 'throw new' and this is the place that the object method is called....
Or if you could somehow use the existing phpunit exception functionality to change the exception behavior the way you want, in a general way for all your code... but this seems like it would be hacky and bad....
EDIT: here is some code to make things clearer:
class FooTest extends PHPUnit_Framework_TestCase{
public function testBar(){
include '/path/to/file.php'; //generates exception
$this->assertTrue($baz);
}
}
...
//overridden exception class
class Foo_Exception extends ErrorException{
...
so, my question, is there a way to deal with this overriden class, without doing it on a case by case basis? what if I'm not testing the behavior of the exception, just the code that causes the exception?
I would first write a test that captures the exception generation behavior:
include '/path/to/file.php'; //generates exception
public function testCatchFooException() {
try {
$this->assertTrue($baz);
}
catch (Exception $expected) {
$this->assertEquals('This is expected html from exception', $expected->getMessage());
return;
}
$this->fail('An expected Exception has not been raised Foo_Excpetion.');
}
Now you can do several things with this coverage test. You can either fix up the exception, or fix the code that causes the exception.
Another thing you can do is wrap the entire file.php in a class:
class FooClass {
function runFoo() {
include '/path/to/file.php'; //generates exception
}
}
Then add tests while using extract method until you isolate exception.
[EDIT]
Here is some serious procedural legacy code:
<?php
require_once 'helper.php'; //helper file
function countNewMessages($user_id) {
}
function countNewOrders() {
}
function countNewReturns() {
}
function getDB($init = NULL) {
}
function getDisplay() {
}
getDisplay();
?>
And here is the wrapped class:
<?php
require_once ''; //helper file
class Displayer {
function countNewMessages($user_id) {
}
function countNewOrders() {
}
function countNewReturns() {
}
function getDB($init = NULL) {
}
function getDisplay() {
}
}
?>
And now I can test it:
function testGetDisplay() {
$display = new Displayer();
$this->assertEquals('html code', $display->getDisplay());
}
And test the individual functions in it. And if I can further sprout methods on it.
The above test would be considered a coverage test. There may be bugs in it, but that is what it does. So as I sprout methods the get more code coverage from tests by sprouting that I can make sure I don't break the output.
The extened PHP exception object "prints" a costum HTML error page? You mean its error message is an entire HTML page? That's not very clever...
What you can do about it is to replace the default exception handler (see this function), call getMessage on the exception and parse the HTML error page to extract the message. Then you can print the error message and kill the script. Like this (in PHP 5.3):
set_exception_handler(
function (Exception $e) {
die(parse_html_error_page($e->getMessage()));
}
);
OK, I misunderstood the question. If the script you're testing catches the error and then echoes an error page, then this has nothing to do with exceptions. You can use the ob_ family:
ob_start();
include $file;
$contents = ob_get_contents();
if (result_is_error($contents))
die(extract_error_from_result($contents));
else
echo $contents;
ob_end_clean();

Categories