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.
CREATE CONSTRAINT unique_email IF NOT EXISTS
FOR (u:User) REQUIRE u.email IS UNIQUE
Your application includes a method called addUser
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 code to handle the constraint error.
public static String createUser(Driver driver, String name, String email) {
try (var session = driver.session()) {
session.executeWrite(
tx -> addUser(
tx,
"Test User",
"test_user@example.com"
)
);
return "{\"success\": true, \"message\": \"User created successfully\"}";
} /*select:catch (ClientException e)*/ {
return "{\"success\": false, \"message\": \"User already exists\"}";
}
}
-
✓ catch (ClientException e)
-
❏ catch (Neo4jException e)
-
❏ except (Exception e)
-
❏ except (ConstraintError e)
Hint
The Cypher statement above creates a constraint on the email
property for the User
label.
Constraint errors are raised as a ClientException
in the Neo4j Java driver.
Solution
The correct answer is catch (ClientException e)
.
public static String createUser(Driver driver, String name, String email) {
try (var session = driver.session()) {
session.executeWrite(
tx -> addUser(
tx,
"Test User",
"test_user@example.com"
)
);
return "{\"success\": true, \"message\": \"User created successfully\"}";
} catch (ClientException e) {
return "{\"success\": false, \"message\": \"User already exists\"}";
}
}
Catching `Neo4jException` would also work, but would be less specific to the constraint error.
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 Java application that connect to Neo4j and the confidence put it into production.
Next Steps
Ready for your next challenge?
The Using Neo4j with Java course will teach you how to connect to Neo4j in your Java applications.