diff --git a/src/errors.ts b/src/errors.ts index b4cc6b93..ee5d1b48 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -7,7 +7,8 @@ * file that was distributed with this source code. */ -import { createError } from '@poppinss/utils' +import { createError, Exception } from '@poppinss/utils' +import { LucidModel } from './types/model.js' export const E_INVALID_DATE_COLUMN_VALUE = createError<[string, string | null]>( 'Invalid value for "%s". %s', @@ -45,7 +46,29 @@ export const E_MODEL_DELETED = createError( 500 ) -export const E_ROW_NOT_FOUND = createError('Row not found', 'E_ROW_NOT_FOUND', 404) +/** + * The "E_ROW_NOT_FOUND" exception is raised when + * no row is found in a database single query + * + * The "error.model" can be used to know the model which + * raised the error. This will only be present when using + * Lucid models not Database queries + */ +export const E_ROW_NOT_FOUND = class extends Exception { + static readonly status: number = 404 + static readonly code: string = 'E_ROW_NOT_FOUND' + static readonly message: string = 'Row not found' + + /** + * The model that raised the error. + */ + model?: LucidModel + + constructor(model?: LucidModel) { + super() + this.model = model + } +} export const E_UNABLE_ACQUIRE_LOCK = createError( 'Unable to acquire lock. Concurrent migrations are not allowed', diff --git a/src/orm/query_builder/index.ts b/src/orm/query_builder/index.ts index f1a68499..ca9ac9a8 100644 --- a/src/orm/query_builder/index.ts +++ b/src/orm/query_builder/index.ts @@ -481,7 +481,7 @@ export class ModelQueryBuilder async firstOrFail(): Promise { const row = await this.first() if (!row) { - throw new errors.E_ROW_NOT_FOUND() + throw new errors.E_ROW_NOT_FOUND(this.model) } return row diff --git a/test/orm/base_model.spec.ts b/test/orm/base_model.spec.ts index 3216fc53..105d1d7c 100644 --- a/test/orm/base_model.spec.ts +++ b/test/orm/base_model.spec.ts @@ -3795,7 +3795,7 @@ test.group('Base Model | fetch', (group) => { }) test('raise exception when row is not found', async ({ fs, assert }) => { - assert.plan(1) + assert.plan(2) const app = new AppFactory().create(fs.baseUrl, () => {}) await app.init() @@ -3817,8 +3817,9 @@ test.group('Base Model | fetch', (group) => { try { await User.findOrFail(1) - } catch ({ message }) { + } catch ({ message, model }) { assert.equal(message, 'Row not found') + assert.equal(model.name, User.name) } })