最佳做法:在用户输入上抛出异常或使用验证器 [英] Best practice: throwing Exception or using Validator on User Input
问题描述
示例:我尝试登录,但我的帐户未激活。作为OO语言的程序员,我可以通过几种方式来处理这个问题。对于这种情况,请坚持这两个:
- 将自定义
异常
从 c \\ c> c以本地 服务
为代表。在类
中处理用户输入。 - 使用
验证器
请致电当地的服务
以检查此帐户是否已登录。
我的视觉像许多其他人一样,异常
表示程序中的故障。例如。数据库无法访问,解析数据时出错。
许多其他人的愿景,登录而不被激活的情况不是任何用例的成功场景,因此失败。这不应该发生,并且值得抛出异常
。
个人来说,我会处理这种验证器
的问题,仅针对程序中的故障,坚持异常
。不过,我希望得到一个建设性的答案,哪个是首选。如有可能,请参考任何文件。我使用 Java
,虽然这个问题不限于任何语言(只要它是OO我猜)。
如果出现验证错误,应用程序的流程必须中断。例如,如果提供的邮件地址无效,您必须终止歌唱进度。因此,异常可以用于用户输入验证的目的。
作为示例,您可以检查JSF。它受益于Java的异常机制来处理用户输入验证。以下链接可能很有用:
- http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/
- http://www.ibm.com/developerworks/library/j- jsf3 /
Recently I've been into multiple arguments on whether to throw an exception on false User Input.
Example: I'm trying to login though my account is not activated. As the programmer in an OO-language, I could handle this in a few ways. For this case, lets stick to these two:
- Throw a custom
Exception
from the localService
with a representative way, extendingException
. Catching this in theclass
handling User Input. - Use a
Validator
to call the localService
to check whether this account is logged in.
My vision, like many others, an Exception
represents a fault in the program. E.g. database unreachable, error in parsing data.
Vision of many others as well, the case of logging in without being activated is not a succesful scenario on any use case and will thus fail. This shouldn't not happen and is worth throwing an Exception
for.
Personally, I would handle this kind of problem with a Validator
, sticking to Exception
s for just the faults in the program. However though, I would like to get a constructive answer on which case is preferred. If possible, referring to any documentation. I'm using Java
, though this problem is not restricted to any language (as long as it's OO I guess).
In case of a validation error, the flow of your application must be interrupted. For example, you must terminate a singing up progress if an invalid mail address supplied. Thus, the exceptions can be used for the purpose of user input validation.
As an example use, you can check JSF. It benefits from exception mechanism of Java to handle user input validations. The following links can be useful:
- http://www.mkyong.com/jsf2/custom-validator-in-jsf-2-0/
- http://www.ibm.com/developerworks/library/j-jsf3/
这篇关于最佳做法:在用户输入上抛出异常或使用验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!