Best way to catch and differentiate errors in a realm function

Hey all,

I’m working on using some cloud functions to persist data to a users collection. My users collection has two unique indexes – username and email. If I attempt to insert a duplicate username or email, the call fails as it should. The error object I receive in my catch block only has two properties – name and message. The message looks like this:

Duplicate key error: E11000 duplicate key error collection: dev.users index: email_1 dup key: { email: "" }

Currently, the only way I can tell that it was a duplicate key error, and which key it failed on is to do something like:

if (error.message.includes('E11000') && error.message.includes("dup key: { email")) {
    // duplicate email error


if (error.message.includes('E11000') && error.message.includes("dup key: { username")) {
    // duplicate username error

This seems a bit verbose and prone to error (what if the error code signature suddenly changes?). Is there a better way to deal with errors in realm functions? I can’t seem to find any documentation on the errors.


1 Like

Yes I’m experiencing the same issue. Basically, my solution is:

Whenever I want to indicate an error to the client that is the result of the developer doing something wrong (i.e., not calling the function correctly or not properly validating user input before calling the function), I simply throw an error and expect the client app to just print the error in the console to inform the developer of their mistake.

However, if I want the function to indicate error information that will ultimately be conveyed to the user, I return those errors through a field in the returned document instead, so that I can be super precise about the cause of the error.

If MongoDB or anyone else has a better solution to this issue, please let me know!