Is it a good or bad idea throwing Exceptions when validating data?

后端 未结 14 917
你的背包
你的背包 2020-12-07 16:27

When validating data, I\'ve gotten into a habit of doing the following:

Note: I don\'t really have individual booleans for each check. This is just

14条回答
  •  無奈伤痛
    2020-12-07 16:48

    I would suggest that using exceptions as described in the question (for flow control within a function) is wrong not usually the best idea. I'd go further and saying validation throwing exceptions isn't the best approach; instead return a Boolean and store a list of validation error messages that can be accessed. An accompanying save method could/should throw an exception if it is called on an invalid object.

    Thus if validate fails validation error messages can be displayed to the user (logged, returned. whatever). If validation passes then you can call save. If you call save on an invalid object then get get an appropriate exception.

    Another potential problem with your example code (depending on requirements of course) is it only throws the first validation error that occurs. Imagine this from a users POV:

    • Click save
    • Get an error message
    • Correct error
    • Click save again
    • Get a different error message. Annoying.

    As a user I'd prefer to get all validation errors returned at once so I can correct them all before trying again.

提交回复
热议问题