i have a class like this:
class myclass {
public function save($params){
// some operations
// posible error
return false;
// some more code
// posible error
return false;
// more code
// if everything is ok
return true;
}
}
but what is the best way to display errors, one idea is make the class return numbers like for example:
public function save($params) {
// some operations
// some error with the db
return 1;
// more code
// some error with a table
retunr 2;
// more code
// if everything is ok
return 0;
}
and wh开发者_运维知识库en al call this function, make a switch in order to display the errors:
$obj = new myclass();
$err = $obj->save($params);
switch($err) {
case 1: echo 'error with the db'; break;
case 2: echo 'error with some table'; break;
default: echo 'object saved!';
}
is this the best way to write this? or there is another way?
Many programming languages give you the option to throw and catch exceptions. Where available, this is generally a better error handling model.
public function save($params) throws SomeException {
// some operations
if (posible error)
throw new SomeException("reason");
}
// client code
try {
save(params);
} catch (SomeException e) {
// log, recover, abort, ...
}
Another advantage of Exceptions is that they will (at least in some languages) give you access to stack trace as well as message.
精彩评论