Should exceptions be used to validate the form?

It might be a n00bish question, but whatever. Can I use exceptions to validate the form? Let's say I have a form that asks users for their name and email address, has the right to do the following?

try { if (empty($_POST["name"])) { throw new UserRegistrationException("Your name cannot be empty."); } if (filter_var($_POST["email"])) { throw new UserRegistrationException("Invalid email"); } // Save new user into database } catch (UserRegistrationException $e) { // Show errors on screen } 

Also, if this is really the right way to do this - if the user sends both an empty name and an invalid email address, will both exceptions be executed or only the one that appears first (name in this case)?

I am using PHP .

+6
source share
2 answers

I personally like to use exceptions for everything that should stop or change the program flow. In other words, if checking a specific field changes the data processing or requires a repetition of the process, I always use an exception to handle errors.

If this is trivial, or I'm just compiling a list of error messages, then I am not throwing an exception.

To answer the questions, two exceptions cannot be excluded at the same time. The first ejection expression to be achieved will be displayed. This does not mean that sometimes it makes no sense to reconstruct as another type of exception.

+4
source

Use case for exceptions - for exceptional conditions. In this case, do you expect the username and password fields to be empty? If you are showing a web form, I would say yes, you are expecting empty username and password fields, and therefore you should explicitly check this condition and not throw an exception.

To answer your specific question, both exceptions will not be thrown if an error occurs. The throw statement sends the program to the catch block. From there, control will proceed as usual.

+4
source

Source: https://habr.com/ru/post/912196/


All Articles