I have a project object.
A user can assign a worker object for it.
99% of the case the project object has all the proper fields set.
In some cases, the project is missing a field.
In order for a worker to be assign to a project the project must have all the required fields setup.
To solve this, I throw exceptions like this: ( don’t try to find a pattern here, the real example is more complex )
if ($project->startDate == false ) {
throw new Exception("Missing startDate attribute for project id: $id");
}
if ($project->finishDate == false ) {
throw new Exception("Missing finishDate attribute for project id: $id");
}
if ($project->startDate > $project->finishDate ) {
throw new Exception("Invalid start date for project id: $id");
}
The problem with this is that I need to display a custom message to the user each time. For example if the first error is thrown the user should see: ‘Please setup the project start date’ and so on.
How can I do this ?
Just define your own exception class and your whole code in a
try .. catch:By the way, if you want to include variable contents in a string, either use double quotes (
"id: $id") or concatenate ('id: ' . $id).