方法返回错误代码或者最好的方法是什么
我有一个这样的类:
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;
}
}
但是显示错误的最佳方法是什么,一个想法是让类返回数字,例如:
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;
}
当调用此函数时,进行切换以显示错误:
$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!';
}
这是最好的吗怎么写这个?或者还有其他方法吗?
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 when 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
许多编程语言都提供抛出和捕获异常的选项。如果可用,这通常是更好的错误处理模型。
异常的另一个优点是它们(至少在某些语言中)使您可以访问堆栈跟踪和消息。
Many programming languages give you the option to throw and catch exceptions. Where available, this is generally a better error handling model.
Another advantage of Exceptions is that they will (at least in some languages) give you access to stack trace as well as message.