Handling errors

Let’s practice error handling in a real-world scenario.

You have built an application that includes a registration form for new users. As part of the setup, you have added a unique constraint on the email property for the User label.

cypher
Creating a unique constraint
CREATE CONSTRAINT unique_email IF NOT EXISTS
FOR (u:User) REQUIRE u.email IS UNIQUE

Your application includes a function called create_user that creates a new user in the database. It does not check for existing users with the same email address, and instead relies on the database to enforce the constraint.

Handle the constraint error

Select the correct function to handle the constraint error.

python
from neo4j.exceptions import ConstraintError

def add_user(tx, name, email):
    try:
        result = tx.run(
            "CREATE (u:User {name: $name, email: $email}) RETURN u",
            name=name, email=email
        )
        return {"success": True, "message": "User created successfully"}
    #select:except ConstraintError as e:
        return {"success": False, "message": f"Email {email} already exists"}
  • ✓ except ConstraintError as e

  • ❏ except UserExistsError as e

  • ❏ except ProgrammingError as e

  • ❏ except PEBKACError as e

Hint

The Cypher statement above creates a constraint on the email property for the User label.

Solution

The correct answer is except ConstraintError as e.

The except ConstraintError as e block will catch the constraint error and return a message to the user.

python
from neo4j.exceptions import ConstraintError

The other options are incorrect because:

  • run() is deprecated and should not be used

  • execute_write() is for write transactions only

  • run_async() is not a valid method for the session object

Lesson Summary

In this challenge you demonstrated how to handle errors in a real-world scenario.

You should now have all of the information needed to build a Python application that connect to Neo4j and the confidence put it into production.

Next Steps

Ready for your next challenge?

The Building real-world Neo4j Applications with Python course will take you through the process of building an API for a movie recommendation website using the skills you have learned in this course.