使用bool(返回类型)来处理异常或将异常传递给客户端? [英] Using bool (return Type) to handle exceptions or pass exception to client?

查看:187
本文介绍了使用bool(返回类型)来处理异常或将异常传递给客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找出最好的处理异常的方法,我有一些层到我的应用程序,并开始使用返回类型的BOOL,如果它失败,然后返回False,如果成功返回True ..



这样在SaveMyRecord(somerecord);因为我传递值,不需要返回任何东西,所以我可以使用bool的返回类型来指示它是否成功。



但是,它让我认为像GetMyRecord()这样的事情实际上会返回IQueryable的类型,所以我不能使用一个bool来告诉我,如果它失败了。



事情是我处理很多我错误的地方,他们发生在尝试和抓住,因此不希望客户端收到例外。



也许有一个更好的方法,我然后想到关于使用OUT参数但是这意味着我需要更改所有方法的签名并添加附加参数。



也许我应该将异常传递给CLIENT并处理它有吗?



有没有一些标准或任何文件来推荐最佳做法?

解决方案

向上泡沫的客户端的异常并处理它。一定要全面通过它。最好的做法几乎完全同意这一点,总是终于在周边处理,在这种情况下,客户端,尽管在其他情况下可能是一个网络服务。



只要抓住即可登录添加更多信息,或尝试从恢复。在每种情况下,您将会将原始内容抛出一个新的异常,或者简单地将原来的抛出原样,并且如所指出的那样,不要抛出



这个问题是重复的 ,您可以在SO上找到很多现有的很好回答的问题。我仅回覆了类似的昨天


I am trying to find out the best way of handling exceptions, I have a number of layers to my application and started to use a return type of BOOL i.e. if it fails then return False and if it succeeds return True..

This works great in methods like SaveMyRecord(somerecord); as i am passing in values and don't require anything returned so i can use the return type of bool to indicate if it succeeds or not.

But then it got me thinking that things like GetMyRecord() actually returns type of IQueryable hence i can't use a bool to tell me if it failed or not.

The thing is i am handle alot of my errors where they happen with try and catch and hence don't want the client to receive an exception.

Maybe there is a better way, i then got thinking about using OUT parameters BUT this means i need to change the signature of all methods and add aditional params..

Maybe i should be passing the exception back to the CLIENT and handling it there?

Is there some standards or any docs to adivse best practices?

解决方案

Bubble up the exception to the CLIENT and handle it there. Definitely pass it in full detail all the way up. Most best practices almost entirely agree on this, always finally handle on the perimeter, in this case the CLIENT, though in other cases that could be a web service.

Only catch if you want to log it, add more info to it or try and recover from a particular exception. In each case you will will either throw a new exception with the original as the inner or simply 'throw' the original as is, and as pointed in comments don't 'throw ex'

This question is a near duplicate and you'd find lots of existing very well answered questions on SO. I answered a similar one only yesterday

这篇关于使用bool(返回类型)来处理异常或将异常传递给客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆