title: Retrieving error status from Haskell MongoDB driver
body: <p>I have a MongoDB with one collection <code>user</code> that contains a unique index on <code>email</code>:</p>
  
  <pre><code>import Data.Bson        (Value (Int32))
  import Database.MongoDB (Index (..), createIndex, (=:))
  
  createIndex $ Index "user" [ "email" =: Int32 1 ] "email" True False
  </code></pre>
  
  <p>I have written a function that inserts a new user if the email address it is not already in use, and should fail if the email address is already taken:</p>
  
  <pre><code>import           Data.Bson        (Value (ObjId))
  import           Database.MongoDB (Action, ObjectId, (=:))
  import qualified Database.MongoDB as M (insert)
  
  data User = User
    { email     :: Text
    , firstName :: Text
    , lastName  :: Text
    } deriving Show
  
  data MongoEntity a = MongoEntity ObjectId a
  
  createIfNotExists :: User
                    -&gt; Action Handler (Either Text (MongoEntity User))
  createIfNotExists (user@User {..}) = do
    value &lt;- M.insert "user" [ "email" =: email
                             , "firstName" =: firstName
                             , "lastName" =: lastName
                             ]
    case value of
      ObjId objectId -&gt; return (Right $ MongoEntity objectId user)
      _ -&gt; return $ Left "no document"
  </code></pre>
  
  <p>I would like to detect any errors throw by the <code>M.insert</code> (such as a duplicate key) and return an
  error <code>Text</code> message.</p>
  
  <p>Since the <code>M.insert</code> runs in the <code>Action</code> monad, I assume it sets an error status if it fails, but I can't figure out how to retrieve it. I assume that I need something like</p>
  
  <pre><code>error &lt;- getErrorStatus -- or whatever it is called
  </code></pre>
  
  <p>immediately after the <code>value &lt;- M.insert ...</code> line and then test the error in the <code>case ... of</code> expression.</p>
  
  <p>By the way, I tried writing <code>createIfNotExists</code> using <code>findAndModify</code> but I couldn't capture a failure with that either.</p>