I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure how to handle errors. For example:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
// Save input
}
}
If I pass invalid input to save, should I throw an exception like this:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
if ( ! validate( 'text', $new_data['name'] ) ) {
throw new Exception( 'Invalid data entered' );
}
// Save input
}
}
Or instead, should I add an extra function and leave it to the view/controller:
if ( $product->save( $data )->has_error() ) {
$error = $product->get_error();
}
echo '<p>' . $error . '</p>';
Don't throw an exception. Exceptions are for exceptional situations - invalid data entered into a form should not trigger an exception.
Your model should have some sort of error state set, either on the model itself or on the individual fields. The post-back should "fall through" and display the same form that was originally shown, with error messages and/or highlighted fields indicating where the error is so the user can fix it.
Throwing exceptions for validation is going to lead to a very fragile and difficult to use system. What happens if you want to simply show the user that one of the fields they supplied is invalid and give them a chance to correct it? How are you going to catch an exception and know how to display the associated record/form?
Throw an exception. Otherwise you'll have to remember always to call has_error/get_error after any operation. And you'll have a lot of duplicated code. And what if the error should be handled not by the method a() that have called save(), but by the method b() that called the method a()? you'll have to return error from a(), and b() will have to check for the error as well.
Related
In my laravel app, say I have a bit of code as follows, as an example
function convert_amount($amount, $currency, $date)
{
if (strlen($currency) <> 3)
{
// Exception thrown
} else {
// convert $amount from $currency on $date
}
return $amount;
}
Here, I am simply converting a number from a currency to base. I perform a simple check to see if the currency string passed is 3 character to ensure it's a ISO currency code (EUR, GBP, USD etc). If not I want to throw an exception but not result in the app falling to an error page like is often the case with Laravel's error handler.
Instead, I'd like to continue processing the page but log the exception and perhaps display an error in a flash message.
Is there a listener I can define for Laravel that achieves this? Do I need to define a new exception type NonFatelException perhaps that does the logic.
Edit
Essentially, I guess I could register a new exception handler like so:
class NonFatalException extends Exception {}
App::error(function(NonFatalException $e)
{
// Log the exception
Log::error($e);
// Push it into a debug warning in the session that can be displayed in the view
Session::push('debug_warnings', $e->getMessage());
});
Then somewhere in my app:
throw new NonFatalException('Currency is the wrong format. The amount was not converted');
The trouble with this is that the default exception handlers will then be called resulting in an error page rather than the page that was going to be reached.
I could return a value in my handler to avoid the default but I believe that would result in that return value alone being shown and the rest of my scripts would not be run.
You are on a right path. Why not use try...catch tho?
Your helper method will be:
function convert_amount($amount, $currency, $date)
{
if (strlen($currency) <> 3)
{
throw new NonFatalException('Currency is the wrong format. The amount was not converted');
} else {
// convert $amount from $currency on $date
}
return $amount;
}
And whenever you'll use it, put it in a try...catch:
try {
convert_amount($amount, $currency, $date);
} catch (NonFatalException $e) {
// Log the exception
Log::error($e);
// Push it into a debug warning in the session that can be displayed in the view
Session::push('debug_warnings', $e->getMessage());
}
This way, your app will never stopp and you have the error message in Session.
I have a class Person.
I want to add error handling into my script, so that say, the user enters an incorrect email address the script will tell them. Usually not a problem at all, but now I am using OO classes I am in unfamiliar territory.
So. I guess I want to know how to handle multiple exceptions. Or do I need to try each line of code one at a time and catch each line? This seems slightly excessive. Ideally I'd like to do the following:
try {
$people[$new]->set_fullname($_POST['name']);
$people[$new]->set_active(true);
$people[$new]->set_add1(rEsc($_POST['add1']));
$people[$new]->set_add2(rEsc($_POST['add2']));
$people[$new]->set_add3(rEsc($_POST['add3']));
$people[$new]->set_add4(rEsc($_POST['add4']));
$people[$new]->set_postcode(rEsc($_POST['postcode']));
$people[$new]->set_phone(rEsc($_POST['phone']));
$people[$new]->set_email(rEsc($_POST['email']));
} catch {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
But in my error handling, How can I catch multiple errors? I'd like to push all the error messages into an array and display them each nicely in the webpage. As far as I can see on php.net it seems that I can only catch one error message at a time.
Do I really have to try {} catch {} each line of code?
Imho this shouldn't throw exceptions in the first place. Simply loop through the fields and add the possible errors to some $errors array.
Users screwing up fields is not an exceptional case. I don't even think the user object should be able to validate an emailaddress. That seems to be like a responsibility of the Form.
Also am I wondering what that rEsc function is you are using. Not only are you using a global function which makes it virtually impossible to swap it out for some other function in the future (tight coupling), but also the name is chosen badly. Also do I fail to see why you would want to escape stuff in that place (I guess that is what the thing does). Only escape / sanitize data when you are using it. And I'm wondering for what you are escaping your data, because if it is for database input there are far better ways.
try {
$people[$new]->set_fullname($_POST['name']);
$people[$new]->set_active(true);
$people[$new]->set_add1(rEsc($_POST['add1']));
$people[$new]->set_add2(rEsc($_POST['add2']));
$people[$new]->set_add3(rEsc($_POST['add3']));
$people[$new]->set_add4(rEsc($_POST['add4']));
$people[$new]->set_postcode(rEsc($_POST['postcode']));
$people[$new]->set_phone(rEsc($_POST['phone']));
$people[$new]->set_email(rEsc($_POST['email']));
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} catch (EmailFormatException $em) {
echo 'Caught exception: '. $e->getMessage();
}
Just continue it like that
Here's how I would design this:
Create a validate() method on the Person class that verifies every property and returns an array of strings that explain the errors to the user. If there are no errors, have the method return null.
Do not use exceptions at all. They are slow; they complicate code maintenance (and you're seeing the symptoms in the approach you've taken so far)
Remove the custom methods for setting properties of the Person object. PHP is not Java. Set the properties directly.
Putting this all together:
class Person {
public $name;
public $address1;
public $address2;
public function validate() { }
}
And then your code:
$obj = new Person();
$obj->name = "Bob";
$obj->address1 = "1 Elm St.";
$validationResult = $obj->validate();
if ( $validationResult != null) { // there were errors
print_r($validationResult);
}
You can make a foreach statement that sets the data that needs validation with try/catch inside the loop in order to populate an array with the errors, like that:
$errors = [];
foreach (['field1', 'field2', ...] as $field) {
try {
$method = "set_{$field}";
$people[$new]->$method(rEsc($_POST[$field]));
} catch (Exception $e) {
$errors[] = $e->getMessage();
}
}
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.
I can't get my head around WHEN to throw and catch exceptions for when I call functions from classes.
Please imagine that my QuizMaker class looks like this:
// Define exceptions for use in class
private class CreateQuizException extends Exception {}
private class InsertQuizException extends Exception {}
class QuizMaker()
{
// Define the items in my quiz object
$quiz_id = null;
$quiz_name = null;
// Function to create a quiz record in the database
function CreateQuizInDatabase()
{
try
{
$create_quiz = // Code to insert quiz
if (!$create_quiz)
{
// There was an error creating record in the database
throw new CreateQuizException("Failed inserting record");
}
else
{
// Return true, the quiz was created successfully
return true;
}
}
catch (CreateQuizException $create_quiz_exception)
{
// There was an error creating the quiz in the database
return false;
}
}
function InsertQuestions()
{
try
{
$insert_quiz = // Code to insert quiz
if (!$insert_quiz)
{
// There was an error creating record in the database
throw new CreateQuizException("Failed inserting quiz in to database");
}
else
{
// Success inserting quiz, return true
return true;
}
}
catch (InsertQuizException $insert_exception)
{
// Error inserting question
return false;
}
}
}
... and using this code, I use the class to create a new quiz in the database
class QuizMakerException extends Exception {}
try
{
// Create a blank new quiz maker object
$quiz_object = new QuizMaker();
// Set the quiz non-question variables
$quiz_object->quiz_name = $_POST['quiz_name'];
$quiz_object->quiz_intro = $_POST['quiz_intro'];
//... and so on ...
// Create the quiz record in the database if it is not already set
$quiz_object->CreateQuizRecord();
// Insert the quiz in to the database
$quiz_object->InsertQuestions();
}
catch (QuizMakerException $quiz_maker_error)
{
// I want to handle any errors from these functions here
}
For this piece of code, I want to call a QuizMakerException if any of the functions don't perform what I want them to (at the moment they return TRUE or FALSE).
What is the correct way to go about catching when any of the functions in this code does not perform what I want them to? At the moment they simply return TRUE or FALSE.
Do I really have to put lots of if/else statements between calling each function, I thought that was the whole point in exceptions, they simply halt the execution of further statements within the try/catch?
Do I throw a QuizMakerException from within the catch of my functions?
What is the right thing to do?
Help!
Well typically in the function which throws the exception, say your InsertQuestions method, you don't want to catch any exceptions, you want to throw them or let ones occurring to "bubble up". Then your "controller" code can make the determination of how to handle the exception.
If your goal here is to halt if CreateQuizRecord fails I would wrap CreateQuizRecord and InsertQuestions each in their own try block.
One advantage of exceptions is they can tell you more than a simple bool pass/fail. Either extending your base exception into things like "Invalid_Parameter" and testing for specific exceptions or -less ideally- inferring from properties of the exception. You can nest your catch blocks to handle exceptions individually.
Do I throw a QuizMakerException from within the catch of my functions?
Yes. Typically your code under // Code to insert quiz would itself return an exception. Say if the Model failed to insert it might be raising a database exception. In which case you can let that database exception bubble up, or do what you sort of doing now and catch it simply to in turn throw another exception (kinda dumbs down your exceptions in a way, doing that though).
Do I really have to put lots of if/else statements between calling each function, I thought that was the whole point in exceptions, they simply halt the execution of further statements within the try/catch?
I look at it like this, each call which throws an exception and is followed by a subsequent call which depends on this one not throwing any exceptions, should be wrapped in a try block. Assuming you want to handle it gracefully, if you simply want it to error out and halt just don't handle the exception. You'll get an error and stack trace. Sometimes that is desirable.
You might want to change the structure a bit. Your class QuizMaker can become:
<?php
// Define exceptions for use in class
public class CreateQuizException extends Exception {}
public class InsertQuizException extends Exception {}
class QuizMaker()
{
// Define the items in my quiz object
$quiz_id = null;
$quiz_name = null;
// Function to create a quiz record in the database
function CreateQuizInDatabase()
{
try
{
$create_quiz = // Code to insert quiz
if (!$create_quiz)
{
// There was an error creating record in the database
throw new CreateQuizException("Failed inserting record");
}
else
{
// Return true, the quiz was created successfully
return true;
}
}
catch (Exception $create_quiz_exception)
{
// There was an error creating the quiz in the database
throw new CreateQuizException(
"Failed inserting record " .
$create_quiz_exception->getMessage()
);
}
}
function InsertQuestions()
{
try
{
$insert_quiz = // Code to insert quiz
if (!$insert_quiz)
{
// There was an error creating record in the database
throw new InsertQuizException("Failed inserting quiz in to database");
}
else
{
// Success inserting quiz, return true
return true;
}
}
catch (Exception $insert_exception)
{
// Error inserting question
throw new InsertQuizException(
"Failed inserting quiz in to database " .
$create_quiz_exception->getMessage()
);
}
}
}
Effectively, if you cannot insert the record correctly, you throw an Insert exception. If anything goes wrong with that block of code, you catch it and throw again an Insert exception. Same goes with the Create function (or any other ones you might have).
In the main block of code you can have:
try
{
// Create a blank new quiz maker object
$quiz_object = new QuizMaker();
// Set the quiz non-question variables
$quiz_object->quiz_name = $_POST['quiz_name'];
$quiz_object->quiz_intro = $_POST['quiz_intro'];
//... and so on ...
// Create the quiz record in the database if it is not already set
$quiz_object->CreateQuizRecord();
// Insert the quiz in to the database
$quiz_object->InsertQuestions();
}
catch (InsertQuizException $insert_exception)
{
// Insert error
}
catch (CreateQuizException $create_quiz_exception)
{
// Create error
}
catch (Exception $quiz_maker_error)
{
// Any other error
}
If you don't want to have the multiple catch block there, just keep the catch(Exception) one and then check in it the type of each exception thrown to specify the actions taken from there.
HTH
The best thing to do is to not have to thhrow exceptions in the first place.
Exceptions are thrown when the program crashes and they are not made to handle wrong output.
If your function returns anything (even its the wrong thing) it doesn't need an exception.
To answer your question, if it's necessaryto use a lot of ifs/elses then you must use them.
Lets assume I have a class called Form. This class uses the magic method __call() to add fields to itself like so:
<?php
class Form {
private $_fields = array();
public function __call($name, $args) {
// Only allow methods which begin with 'add'
if ( preg_match('/^add/', $name) ) {
// Add a new field
} else {
// PHP throw the default 'undefined method' error
}
}
}
My problem is that I can't figure out how to make PHP handle the calls to undefined methods in it's default way. Of course, the default behavior can be mimicked in many ways, for example I use the following code right now:
trigger_error('Call to undefined method ' . __CLASS__ . '::' . $function, E_USER_ERROR);
But I don't like this solution because the error itself or its level might change in the future, so is there a better way to handle this in PHP?
Update
Seems like my question is a little vague, so to clarify more... How can I make PHP throw the default error for undefined methods without the need to supply the error and it's level? The following code won't work in PHP, but it's what I'm trying to do:
// This won't work because my class is not a subclass. If it were, the parent would have
// handled the error
parent::__call($name, $args);
// or is there a PHP function like...
trigger_default_error(E_Undefined_Method);
If anyone is familiar with ruby, this can be achieved by calling the super method inside method_missing. How can I replicate that in PHP?
Use exceptions, that's what they're for
public function __call($name, $args) {
// Only allow methods which begin with 'add'
if ( preg_match('/^add/', $name) ) {
// Add a new field
} else {
throw new BadMethodCallException('Call to undefined method ' . __CLASS__ . '::' . $name);
}
}
This is then trivially easy to catch
try {
$form->foo('bar');
} catch (BadMethodCallException $e) {
// exception caught here
$message = $e->getMessage();
}
If you want to change error level, just change it when necessary or add if statement instead of E_USER_ERROR