I'm working on an app that simulates a social media site. I currently have a form where users can enter in their friends' emails so they can be invited to join the app.
Let's say we have a user who enters in three email addresses to the email form which are then saved as a list of strings:
emails_to_invite = ["[email protected]", "[email protected]", "[email protected]"]
In the database, we already have a list of users who have already been invited to the site:
current_users = ["[email protected]", "[email protected]", "[email protected]", "[email protected]"]
So we have two users who have already been invited: [email protected] and [email protected].
I'm trying to write some code that returns a ValidationError and can list both matched users in the message. Here's what I have so far:
for email in emails_to_invite:
if email in current_users:
raise forms.ValidationError(f"{email} is already in the database.")
Here's how I want this error to display:
[email protected] is already in the database.
[email protected] is already in the database.
But right now, the error only displays the first email:
[email protected] is already in the database.
I also need [email protected] to display too. It appears that the for loop stops once it recognizes one match, but I need it to keep going until it recognizes all matches. Can anyone offer some suggestions?
CodePudding user response:
If you don't want an Exception
in a code-block to halt your execution (and hide further exceptions, as you've found), put the susceptible code in a a try/except
block to handle the error as you see fit.
To later raise the exception, consider using something like:
raised_exceptions = []
<loop that might raise exceptions>
try:
<loop that might raise exceptions>
except Exception as e:
raised_exceptions.append(e)
<do something with the exceptions you saved>
That being said, IMO you shouldn't be using exceptions in this way - consider returning a series of lists, one per possible outcome, instead: email sent
and already invited
(and/or joined user
)