blazing-edge-labs / api-skeleton

3 stars 1 forks source link

Simpler Error Handling #13

Closed rkatic closed 5 years ago

rkatic commented 5 years ago

Error Creation

The error() function is now intended as the primary error factory with improved defaults for common error codes to make usage more simpler/concise and errors more consistent.

error('user.not_found') // --> GenericError 404 (error code ending with ".not_found")

error('http.unauthorized') // --> HttpError 401 (http.* values are default statuses)

error('some.error') // --> GenericError 400

error('some.other_error', nestedErrorOrNull, 403) // --> GenericError 403

DB Error Handling

The error.db function is intended as replacement for all DB query error handling, with some important additional benefits:

return db.one(`SELECT * FROM "user" WHERE "email" = $1`, [email])
.catch(error.db({
  noData: 'user.not_found',
}))

await db.query(`
  UPDATE "user"
  SET "email" = $2
  WHERE "id" = $1
`, [id, email])
.catch(error.db({
  user_email_key: 'user.duplicate',
}))

await db.query('DELETE FROM password_token WHERE user_id = $1', [userId])
.catch(error.db) // ensure DB errors are wrapped in a DatabaseError

Please, let me know if you have any concern or objections.