Sign In Register

How can we help you today?

Start a new topic
Answered

Catching mongodb duplicate key error (E11000)

How can the duplicate key error can be detected on MyCollection.insert(document) and trigger some custom game logic.

The simplest example would be displaying something like "this username is already taken" instead of generating a GameSparksErrorResponse.



Best Answer
Hey Gabriel,

The simplest way to get some game logic running only when the e11000 error is thrown would be to use a try-catch. You can send whatever unique error key you want back to your client-code with the Sparks.setScriptError() function.
This will catch any error that gets thrown though, so you'll have to check for the 11000 error-key too, then you can stick whatever code you want to execute in there.

try
{
   // insert code here
}
catch(error)
{
    if(error.message.indexOf("11000") != -1)
    {
        // run some code here //
        Spark.setScriptError("ERROR", "ID already taken");
    }
}

Hope that helps,
- Sean

 

1 Comment

Answer
Hey Gabriel,

The simplest way to get some game logic running only when the e11000 error is thrown would be to use a try-catch. You can send whatever unique error key you want back to your client-code with the Sparks.setScriptError() function.
This will catch any error that gets thrown though, so you'll have to check for the 11000 error-key too, then you can stick whatever code you want to execute in there.

try
{
   // insert code here
}
catch(error)
{
    if(error.message.indexOf("11000") != -1)
    {
        // run some code here //
        Spark.setScriptError("ERROR", "ID already taken");
    }
}

Hope that helps,
- Sean

 

Login to post a comment