Handling duplicate key (and other errors) on insert

146 views
Skip to first unread message

Justin Heyes-Jones

unread,
Jan 25, 2014, 12:28:47 PM1/25/14
to clojure...@googlegroups.com
Sorry if I missed this in the documentation, but I'm having trouble figuring out how to handle a duplicate key error when returned from a monger insert.

          (let [result (monger-collection/insert user-collection-name new-user)]
            (if (monger-result/has-error? result)
              (cheshire/generate-string {:error "Something went wrong"})
              (cheshire/generate-string new-user)))
          (catch Throwable t
            (error-response t)))))

Initially I thought the has-error? function would do the trick but an exception is thrown instead. In catching that I seem to get the raw response of the mongodb as the Throwable's message, so I started to decode and parse that, but is there some way I could do that with monger's API? 

Ultimately I want to just grab the error code and return that to the client.

Justin

Michael Klishin

unread,
Jan 26, 2014, 12:13:16 AM1/26/14
to Monger, a Clojure MongoDB driver

2014/1/25 Justin Heyes-Jones <just...@gmail.com>

Initially I thought the has-error? function would do the trick but an exception is thrown instead. In catching that I seem to get the raw response of the mongodb as the Throwable's message, so I started to decode and parse that, but is there some way I could do that with monger's API? 

Ultimately I want to just grab the error code and return that to the client.

Justin Heyes-Jones

unread,
Jan 26, 2014, 3:01:03 PM1/26/14
to clojure...@googlegroups.com
Ah I see, that helps.

Initially I'm going to just catch MongoException and return the result of getCode. It seems it would fit into the API somewhere like you suggest.

Justin

Michael Klishin

unread,
Jan 26, 2014, 3:39:17 PM1/26/14
to Monger, a Clojure MongoDB driver

2014-01-27 Justin Heyes-Jones <just...@gmail.com>

Initially I'm going to just catch MongoException and return the result of getCode. It seems it would fit into the API somewhere like you suggest.

Sure. Once you feel confident that your approach works well, feel free to submit
a pull request to Monger.
Reply all
Reply to author
Forward
0 new messages