Monday, 17 April 2017

Sailsjs error handling with database / waterline errors

I'm building an api that receives webhook data (orders from shopify) and saves them to a relational mysql database. Each order has products in it that belong to collections (categories). I relate the product to the collection, or create a new collection if it doesn't already exist. The problem I run into is that since I can't use findOrCreate() I do a find() first, and then if nothing is found I do a create. However, since nodejs is async, if I get many orders coming in at once, sometimes the same collection isn't found for two different products at the same time, and then one will create it right before the other one tries, so when the other one tries to create it waterline throws an error:

col_id • A record with that col_id already exists (405145674).

What is the best way to catch this error so I can just do another find() so the function returns the proper collection instead of an undefined? I could just do this:

if (err){ findmethodagain(); }

But then it would try that for any error, not a "record with that id already exists" error.



via hamncheez

No comments:

Post a Comment