Every Narsil package reports a failure with a code, which your program can branch on, and a message, which you can log or show to a person. The four packages give the same code for the same failure. In TypeScript, the engine throws a NarsilError with code, message, and details, which contains the values behind the failure. In Python, the engine raises a narsil.NarsilError with code and message, while in Go, it returns an *engine.Error with Code, Message, and Details. In Rust, a method that fails returns a narsil::NarsilError, whose code() method returns an ErrorCode and whose message() method returns the text. The Python and Rust errors have no details.
On this page, you'll build one program that reads one failure, recovers from the failure that you expect, and collects the failures from a batch. The file is catalogue.ts in TypeScript, catalogue.py in Python, main.go in Go, and src/main.rs in Rust. Each code block shows the whole file, with green lines marking the lines that you add at each step and struck lines marking the lines that you remove.
Read what a failure contains
When you insert a document under the id of a stored document, the engine refuses the insert with DOC_ALREADY_EXISTS. Each program below catches that failure and prints the fields that the error has in its language.
import { createNarsil, isNarsilError } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('products', {
schema: { name: 'string', price: 'number', category: 'enum' },
required: ['price'],
})
await narsil.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 740, category: 'city' })
try {
await narsil.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 760, category: 'city' })
} catch (error) {
if (!isNarsilError(error)) throw error
console.log(JSON.stringify({ code: error.code, message: error.message, details: error.details }, null, 2))
}
await narsil.shutdown(){
"code": "DOC_ALREADY_EXISTS",
"message": "Document \"urban-commuter\" already exists in partition 0",
"details": {
"docId": "urban-commuter",
"partitionId": 0
}
}In TypeScript and Go, the details contain the id and the number of the partition that stores the document, so you can log both without parsing the message. Branch on the code and never on the message, because the code for a failure is the same in every release, while the wording of a message can change. isNarsilError in TypeScript and engine.AsError in Go each return false for an error from outside Narsil, so each program passes such an error on unchanged. In Python, the except NarsilError clause catches only Narsil's errors, so every other exception passes through it. In Rust, every error that a method of the crate returns is a NarsilError, because each of those methods returns narsil::Result.
Recover from the failure that you expect
The TypeScript, Go, and Rust packages give each code a name that the compiler checks, so your editor can complete each name, while the compiler rejects a misspelt one. The TypeScript package exports every code as a constant in ErrorCodes. The Go module declares constants such as engine.CodeDocAlreadyExists, while the Rust crate declares variants of ErrorCode such as ErrorCode::DOC_ALREADY_EXISTS. In Python, a code is a string such as "DOC_ALREADY_EXISTS". In Go, engine.ErrorCode(err) returns the code inside any error, or an empty string for an error from outside Narsil. The engine has no upsert method, so the saveProduct function below, which is save_product in Python and Rust, inserts a product and updates it when the engine refuses the insert with DOC_ALREADY_EXISTS. The function passes every other error on to its caller.
import { createNarsil, isNarsilError } from '@delali/narsil'
import { createNarsil, ErrorCodes, isNarsilError } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('products', {
schema: { name: 'string', price: 'number', category: 'enum' },
required: ['price'],
})
await narsil.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 740, category: 'city' })
try {
await narsil.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 760, category: 'city' })
} catch (error) {
if (!isNarsilError(error)) throw error
console.log(JSON.stringify({ code: error.code, message: error.message, details: error.details }, null, 2))
}
interface Product {
id: string
name: string
price: number
category: string
}
const saveProduct = async (product: Product): Promise<'inserted' | 'updated'> => {
try {
await narsil.insert('products', { ...product })
return 'inserted'
} catch (error) {
if (!isNarsilError(error) || error.code !== ErrorCodes.DOC_ALREADY_EXISTS) throw error
await narsil.update('products', product.id, { ...product })
return 'updated'
}
}
const outcomes = [
await saveProduct({ id: 'cargo-hauler', name: 'Cargo hauler', price: 1890, category: 'cargo' }),
await saveProduct({ id: 'urban-commuter', name: 'Urban commuter', price: 760, category: 'city' }),
]
const commuter = await narsil.get('products', 'urban-commuter')
console.log(JSON.stringify({ outcomes, commuterPrice: commuter?.price }, null, 2))
await narsil.shutdown(){
"outcomes": [
"inserted",
"updated"
],
"commuterPrice": 760
}The function stores the cargo hauler on the first call. On the second call, however, the engine refuses the insert with DOC_ALREADY_EXISTS, so the function replaces the stored commuter, whose price changes from 740 to 760. The function passes every other failure on to its caller, so when you save a product whose price is text, the caller receives DOC_VALIDATION_FAILED. update checks required in the same way as insert, so the engine refuses a product without a price with DOC_MISSING_REQUIRED_FIELD on either path through the function.
Collect the failures from a batch
For a batch insert, the engine stores every document that it can and lists each failure with the id of its document, so it raises no error for a document that fails. Check the failures after every batch.
import { createNarsil, ErrorCodes, isNarsilError } from '@delali/narsil'
const narsil = await createNarsil()
await narsil.createIndex('products', {
schema: { name: 'string', price: 'number', category: 'enum' },
required: ['price'],
})
await narsil.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 740, category: 'city' })
interface Product {
id: string
name: string
price: number
category: string
}
const saveProduct = async (product: Product): Promise<'inserted' | 'updated'> => {
try {
await narsil.insert('products', { ...product })
return 'inserted'
} catch (error) {
if (!isNarsilError(error) || error.code !== ErrorCodes.DOC_ALREADY_EXISTS) throw error
await narsil.update('products', product.id, { ...product })
return 'updated'
}
}
const outcomes = [
await saveProduct({ id: 'cargo-hauler', name: 'Cargo hauler', price: 1890, category: 'cargo' }),
await saveProduct({ id: 'urban-commuter', name: 'Urban commuter', price: 760, category: 'city' }),
]
const commuter = await narsil.get('products', 'urban-commuter')
console.log(JSON.stringify({ outcomes, commuterPrice: commuter?.price }, null, 2))
const imported = await narsil.insertBatch('products', [
{ id: 'gravel-tourer', name: 'Gravel tourer', price: 1340, category: 'gravel' },
{ id: 'cargo-hauler', name: 'Cargo hauler', price: 1890, category: 'cargo' },
{ id: 'folding-city', name: 'Folding city bike', category: 'city' },
])
console.log(
JSON.stringify(
{
outcomes,
stored: imported.succeeded,
failed: imported.failed.map(({ docId, error }) => ({ docId, code: error.code, details: error.details })),
},
null,
2
)
)
await narsil.shutdown(){
"outcomes": [
"inserted",
"updated"
],
"stored": [
"gravel-tourer"
],
"failed": [
{
"docId": "folding-city",
"code": "DOC_MISSING_REQUIRED_FIELD",
"details": {
"field": "price"
}
},
{
"docId": "cargo-hauler",
"code": "DOC_ALREADY_EXISTS",
"details": {
"docId": "cargo-hauler",
"partitionId": 0
}
}
]
}The engine stores the gravel tourer and lists a failure for each of the other two documents. In all four languages, the engine lists the missing price ahead of the duplicate, although the program sends the duplicate first. For that reason, match each failure to its document by its id, and never by its place in the list. Each failure contains an error of the same type as the error that the engine raises for a single insert, with the same code.
Catch an error from any entry point
This section is about the TypeScript packages, because @delali/narsil/server and @delali/narsil/client are TypeScript entry points. A Python or Go program can call the same server through the Python client or the Go client.
Each of the TypeScript entry points @delali/narsil, @delali/narsil/client, and @delali/narsil/react contains a separate copy of the NarsilError class, so an instanceof test against one copy returns false for an error that the constructor of another copy creates. isNarsilError tests for a marker that the constructor of every copy writes into the error, which is why it returns true for an error from any entry point. In remote.ts, the HTTP server serves the catalogue from the engine, while the client sends the duplicate insert again. Install uWebSockets.js first, following the steps on the HTTP server page.
import { createNarsil, NarsilError } from '@delali/narsil'
import { createNarsilClient, isNarsilError } from '@delali/narsil/client'
import { createServer } from '@delali/narsil/server'
const engine = await createNarsil()
await engine.createIndex('products', { schema: { name: 'string', price: 'number', category: 'enum' } })
await engine.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 740, category: 'city' })
const server = createServer(engine, { host: '127.0.0.1', port: 7700 })
await server.listen()
const client = createNarsilClient({ url: 'http://127.0.0.1:7700' })
try {
await client.insert('products', { id: 'urban-commuter', name: 'Urban commuter', price: 760, category: 'city' })
} catch (error) {
if (!isNarsilError(error)) throw error
console.log(
JSON.stringify({ instanceOfEngineClass: error instanceof NarsilError, code: error.code, details: error.details }, null, 2)
)
}
await server.shutdown(){
"instanceOfEngineClass": false,
"code": "DOC_ALREADY_EXISTS",
"details": {
"docId": "urban-commuter",
"partitionId": 0,
"status": 409
}
}The client throws the code that the server sends and adds the HTTP status, 409 here, to details. The instanceof test against the class from @delali/narsil returns false for that error, although isNarsilError returns true for it a line earlier. When the server refuses a request before it passes the request to the engine, as it does for a body over the size limit, the error has a code from ServerErrorCodes. When the failure is on the caller's side, the error has a code from ClientErrorCodes, such as CLIENT_CONNECTION_FAILED when the client can't connect to a server at the address.
See the codes and their HTTP statuses
The table below lists the codes that appear in these docs, along with the status that the HTTP server returns for each one. ErrorCodes contains every other code.
| Code | Cause | Status |
|---|---|---|
DOC_ALREADY_EXISTS | You insert a document under the id of a stored document. | 409 |
DOC_NOT_FOUND | You update or remove a document under an id that the index lacks. | 404 |
DOC_VALIDATION_FAILED | You write a field value of the wrong type, text that contains half of a surrogate pair, a field that the schema of a strict index lacks, or a docId that differs from the document's id. | 400 |
DOC_MISSING_REQUIRED_FIELD | You insert or update a document without a field that required lists. | 400 |
INDEX_NOT_FOUND | You give the name of an index that the engine lacks. | 404 |
INDEX_ALREADY_EXISTS | You create an index under the name of an existing index. | 409 |
SCHEMA_INVALID_TYPE | You give a schema field a type that Narsil does not support. | 400 |
SCHEMA_DEPTH_EXCEEDED | You nest a field five levels deep, as in a.b.c.d.e. | 400 |
SCHEMA_INVALID_VECTOR_DIMENSION | You create an index with a vector field of more than 4,096 dimensions. | 400 |
SEARCH_INVALID_FIELD | You filter on a field that the schema lacks, put a field in fields that the schema lacks or that contains no text, boost a field that the schema lacks, sort on a plain string or a geopoint field, group on a vector field, set vectors in a document projection to a value other than true or false, or sort, facet, or group a strict index on a field that its schema lacks. | 400 |
SEARCH_INVALID_FILTER | You test a plain string field with eq, in, startsWith, or another test of whole values, which needs string:pattern, or you filter with an operator or a unit that Narsil does not support, with startsWith on a number field, with between and one bound, with a negative radius, with a polygon of fewer than three points, with a list of more than 65,536 values, or with more than 1,024 tests. | 400 |
SEARCH_INVALID_MODE | You give a search mode that Narsil does not support, set a sort on a hybrid query, or sort in a direction other than asc and desc. | 400 |
SEARCH_INVALID_PHRASE | You search for a phrase of more than 32 words, or for a phrase on an index with trackPositions off. | 400 |
SEARCH_WORK_CAP_EXCEEDED | The pattern tests and phrases of one search need more work than the patternWorkCap engine setting allows. | 400 |
SEARCH_INVALID_CURSOR | You pass a cursor that the engine cannot decode, or you send a cursor back with a different term, filter, or sort from those of the query that returns it. | 400 |
SEARCH_RESULT_WINDOW_EXCEEDED | You ask through offset and limit for results past the first 10,000. | 400 |
PARTITION_CAPACITY_EXCEEDED | You write past the capacity of an index's partitions, or rebalance past maxPartitions. | 409 |
CONFIG_INVALID | You set an option to a value that the engine does not accept, or set an option that the engine lacks. | 400 |
EMBEDDING_FAILED | Your embedding adapter fails to embed a document or a query. | 503 |
MEMORY_WRITE_BLOCKED | You insert or update while the engine's memory is above the memory.blockWritesAbove share of its limit. | 429 |
PERSISTENCE_SAVE_FAILED | You write or checkpoint while the durability directory is missing. | 503 |
INSTANCE_SHUT_DOWN | You call the engine once shutdown starts. | 503 |
For a code missing from its mapping, the server returns status 500. The server also replaces any error from outside Narsil with INTERNAL_ERROR and a generic message, so that the caller receives no stack trace.
Turn a misspelt field name into an error
On every index, the engine refuses a filter, fields, or boost on a field outside the schema with SEARCH_INVALID_FIELD, because it answers each of them only from the structures that it builds for the fields that the schema declares. On an index without strict, however, a sort, a facet, or a group can refer to a field outside the schema. In that case, the engine answers from the values that your documents contain under that name. A misspelt field name in one of those three options therefore raises no error, because the engine treats the name as a field that no document contains:
- The engine leaves the hits in id order under a sort on that field, whichever direction you give.
- The engine returns a facet on that field with no values and a count of 0.
- When you group on that field, the engine returns one group, whose values contain nothing for that field.
On an index that you create with strict: true, the engine refuses every document that contains a field outside the schema. On that index, it therefore throws SEARCH_INVALID_FIELD for a sort, a facet, or a group on such a field, which means that it refuses any query to a strict index that refers to a field outside the schema.
Where to go next
- Read Indexes and documents for the writes behind most of these codes.
- Read Filters and facets for the filter operators that each field type accepts.
- Read HTTP server for the server that maps each code to a status.
- Read Python, Go, and Rust for the error type of each language in full.