最佳做法:在用户输入上抛出异常或使用验证器 [英] Best practice: throwing Exception or using Validator on User Input

查看:163
本文介绍了最佳做法:在用户输入上抛出异常或使用验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我已经有了多个参数,说明是否在虚拟用户输入中引发异常。



示例:我尝试登录,但我的帐户未激活。作为OO语言的程序员,我可以通过几种方式来处理这个问题。对于这种情况,请坚持这两个:


  1. 将自定义异常从 c \\ c> c 以本地服务为代表。在中处理用户输入。

  2. 使用验证器请致电当地的服务以检查此帐户是否已登录。

我的视觉像许多其他人一样,异常表示程序中的故障。例如。数据库无法访问,解析数据时出错。



许多其他人的愿景,登录而不被激活的情况不是任何用例的成功场景,因此失败。这不应该发生,并且值得抛出异常



个人来说,我会处理这种验证器的问题,仅针对程序中的故障,坚持异常。不过,我希望得到一个建设性的答案,哪个是首选。如有可能,请参考任何文件。我使用 Java ,虽然这个问题不限于任何语言(只要它是OO我猜)。

解决方案

如果出现验证错误,应用程序的流程必须中断。例如,如果提供的邮件地址无效,您必须终止歌唱进度。因此,异常可以用于用户输入验证的目的。



作为示例,您可以检查JSF。它受益于Java的异常机制来处理用户输入验证。以下链接可能很有用:




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:

  1. Throw a custom Exception from the local Service with a representative way, extending Exception. Catching this in the class handling User Input.
  2. Use a Validator to call the local Service 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 Exceptions 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:

这篇关于最佳做法:在用户输入上抛出异常或使用验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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