Skip to content

Commit

Permalink
feat(model_query_builder): add error.model for E_ROW_NOT_FOUND; (#1081
Browse files Browse the repository at this point in the history
)
  • Loading branch information
radiumrasheed authored Dec 23, 2024
1 parent ac8ee6c commit 334186f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
27 changes: 25 additions & 2 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down
2 changes: 1 addition & 1 deletion src/orm/query_builder/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,7 +481,7 @@ export class ModelQueryBuilder
async firstOrFail(): Promise<any> {
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
Expand Down
5 changes: 3 additions & 2 deletions test/orm/base_model.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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)
}
})

Expand Down

0 comments on commit 334186f

Please sign in to comment.