全局异常处理 VS Try catch 无处不在 [英] Global exception handling VS Try catch everywhere

查看:38
本文介绍了全局异常处理 VS Try catch 无处不在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我在我的代码中使用了全局异常处理,我开始知道通过这个可以处理所有异常.以前我在每个控制器上都使用 try-catch,现在我已经从控制器中删除了所有 try-catch,因为它可以处理所有类型的异常.

Recently I have used Global exception handling in my code and I came to know that with this all exceptions can be handled. Previously I was using try-catch at each controller and now I have removed all the try-catch from controller because of Global exception as it can handle all types of exception.

所以我怀疑,删除我之前在控制器中用于全局异常处理的所有异常处理或者应该同时使用全局和控制器上的 try-catch 是否是一个好习惯.

So I doubt that, is it a good practice to remove all the exception handling I have previously used in the controller for Global Exception handling or should use both Global, as well as try-catch at the controller.

如果需要 try-catch,是否有必要在控制器级别处理所有异常.

And if try-catch is required, is it necessary that all the exceptions are to be handled at the controller level.

我当前的工作堆栈是 - .Net Core.

My current working stack is - .Net Core.

推荐答案

这个问题太宽泛,无法给出完整的答案,但让我就这个问题发表我的看法.

The question is too broad to give a full answer but, let me give my opinion on this matter.

try-catch-finally 块不用于处理未处理的异常.自然而然,您从未想过的案件将得不到处理,您不应该让他们保持沉默,而应该让他们表达自己,以便您思考.处理异常虽然是程序员无法处理但他/她已经考虑过的情况.例如用户输入的是字符串而不是数字.

try-catch-finally blocks are not used to handle unhandled exceptions. Naturally the cases that you never thought of will be unhandled and you should not keep them silent but you should allow them to express themselves for you to think about them. Handled exceptions though are the cases that are not at the hand of the programmer but he/she has thought about them. For example user input is string instead of number.

如果情况是您想的但在您的控制范围内,请始终使用 if 进行检查.例如,如果某些内容可以为空.Try-catch 非常昂贵,并且不应在其中处理任何逻辑.

If it's the case that you thought but is in your control always check with ifs. For example if something can be null. Try-catch is really costly and no logic should be handled in them.

另一方面,使用全局异常处理程序正好相反.并不是要包装所有想法案例并向用户显示单个响应.您应该记录未知的异常以返回并思考它们发生的原因,同时向用户说声抱歉.:)

Using a global exception handler on the other hand is the exact opossite. It is not to wrap all thought cases and show a single response to user. You should log unknown exceptions to come back and think about why they happened and in the mean time say that you are sorry to user. :)

这篇关于全局异常处理 VS Try catch 无处不在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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