From 72b64e818e2da0cc03062f0bf454ecc5bbfc9133 Mon Sep 17 00:00:00 2001 From: Faris Ansari Date: Wed, 20 Nov 2019 15:08:32 +0530 Subject: [PATCH] feat: Throw better errors --- backends/sqlite.js | 26 +++++++++++++++++++++----- common/errors.js | 17 +++++++++++++++++ 2 files changed, 38 insertions(+), 5 deletions(-) diff --git a/backends/sqlite.js b/backends/sqlite.js index 00e51c44..55323a7d 100644 --- a/backends/sqlite.js +++ b/backends/sqlite.js @@ -1,9 +1,10 @@ const frappe = require('frappejs'); const sqlite3 = require('sqlite3').verbose(); const Database = require('./database'); +const errors = require('frappejs/common/errors'); const debug = false; -module.exports = class sqliteDatabase extends Database { +class SqliteDatabase extends Database { constructor({ dbPath }) { super(); this.dbPath = dbPath; @@ -237,7 +238,7 @@ module.exports = class sqliteDatabase extends Database { this.conn.run(query, params, (err) => { if (err) { console.error('Error in sql:', query); - let Error = this.getError(err.errno); + let Error = this.getError(err); reject(new Error()); } else { resolve(); @@ -262,7 +263,7 @@ module.exports = class sqliteDatabase extends Database { try { await this.run('commit'); } catch (e) { - if (e.errno !== 1) { + if (e.name !== 'CannotCommitError') { throw e; } } @@ -300,9 +301,24 @@ module.exports = class sqliteDatabase extends Database { } } - getError(errCode) { + getError(err) { + if (err.message.includes('FOREIGN KEY')) { + return frappe.errors.LinkValidationError; + } + if (err.message.includes('SQLITE_ERROR: cannot commit')) { + return SqliteDatabase.CannotCommitError; + } return { 19: frappe.errors.DuplicateEntryError - }[errCode] || Error; + }[err.errno] || Error; } } + +SqliteDatabase.CannotCommitError = class CannotCommitError extends errors.DatabaseError { + constructor(message) { + super(message); + this.name = 'CannotCommitError'; + } +} + +module.exports = SqliteDatabase; diff --git a/common/errors.js b/common/errors.js index 7daad6a2..876e807a 100644 --- a/common/errors.js +++ b/common/errors.js @@ -37,6 +37,20 @@ class DuplicateEntryError extends ValidationError { } } +class LinkValidationError extends ValidationError { + constructor(message) { + super(message); + this.name = 'LinkValidationError'; + } +} + +class DatabaseError extends BaseError { + constructor(message) { + super(500, message); + this.name = 'DatabaseError'; + } +} + class ValueError extends ValidationError {} class Conflict extends ValidationError {} @@ -56,11 +70,14 @@ function throwError(message, error = 'ValidationError') { frappe.throw = throwError; module.exports = { + BaseError, ValidationError, ValueError, Conflict, NotFoundError, ForbiddenError, DuplicateEntryError, + LinkValidationError, + DatabaseError, throw: throwError };