Error Handling
jcell provides typed error classes for structured error handling.
Error Hierarchy
JcellError (base)
├── ValidationError — Document validation failed
├── DuplicateError — Duplicate document ID
└── NotFoundError — Document not found
All errors inherit from JcellError so you can catch any jcell-specific error:
import { JcellError } from '@sajjadbzn/jcell'
try {
await collection.insert({ ... })
} catch (err) {
if (err instanceof JcellError) {
// Handle any jcell error
console.error('jcell error:', err.message)
}
}
ValidationError
Thrown when a document fails schema validation on insert or update.
import { ValidationError } from '@sajjadbzn/jcell'
try {
await collection.insert({ name: 42 } as any)
} catch (err) {
if (err instanceof ValidationError) {
console.error(err.message)
// "Validation failed:\nInvalid value for field "name": expected string, got number"
}
}
Common causes:
- Missing required field
- Wrong type for value
- Unknown field (not in schema)
- Invalid enum value
- Invalid nested object/array
DuplicateError
Thrown when trying to insert a document with an id that already exists.
import { DuplicateError } from '@sajjadbzn/jcell'
try {
await collection.insert({ id: 'existing-id', name: 'Alice' })
} catch (err) {
if (err instanceof DuplicateError) {
console.error(err.message)
// 'Document with id "existing-id" already exists'
}
}
NotFoundError
Thrown by firstOrFail() when no document matches the filter.
import { NotFoundError } from '@sajjadbzn/jcell'
try {
const user = await users.firstOrFail({ id: 'non-existent' })
} catch (err) {
if (err instanceof NotFoundError) {
console.error(err.message)
// 'Document matching filter not found'
}
}
Best Practices
Catching Specific Errors
import { ValidationError, DuplicateError, NotFoundError } from '@sajjadbzn/jcell'
try {
await collection.insert({ id: 'test', name: 42 } as any)
} catch (err) {
if (err instanceof ValidationError) {
// Schema validation failed
} else if (err instanceof DuplicateError) {
// Duplicate ID
} else {
// Unknown error
throw err
}
}
In Express
app.post('/users', async (req, res) => {
try {
const user = await users.insert(req.body)
res.status(201).json(user)
} catch (err) {
if (err instanceof ValidationError) {
res.status(400).json({ error: err.message })
} else if (err instanceof DuplicateError) {
res.status(409).json({ error: err.message })
} else {
res.status(500).json({ error: 'Internal server error' })
}
}
})
In Hono
app.post('/users', async (c) => {
try {
const user = await users.insert(await c.req.json())
return c.json(user, 201)
} catch (err) {
if (err instanceof ValidationError) return c.json({ error: err.message }, 400)
if (err instanceof DuplicateError) return c.json({ error: err.message }, 409)
throw err
}
})