使用布尔(返回类型)来处理异常或传递异常客户端?异常、布尔、客户端、类型

2023-09-04 01:22:21 作者:一路荒凉如歌

我试图找出异常处理的最佳方式,我有许多层,以我的应用程序,并开始使用BOOL即返回类型,如果失败则返回假,如果它成功返回True ..

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..

这像SaveMyRecord(somerecord)方法的伟大工程;由于我传递价值,不需要返回,所以我可以用布尔的返回类型来表明它是成功还是没有什么。

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.

但后来它让我想,像GetMyRecord()实际返回的IQueryable的类型,因此我不能用一个布尔值来告诉我,如果它失败与否。

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.

事情是我是处理了很多我的错误,他们发生在try和catch,因此不希望客户端收到异常。

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.

也许有更好的方法,我便起身想使用OUT参数,因为这意味着我需要改变的所有方法的签名,并添加aditional的PARAMS ..

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?

有一些标准或文档到adivse最佳做法?

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'

这个问题是一个近似重复,然后你会发现很多的SO已有很好回答问题的。我回答了similar 之一就在昨天

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