Error Handling
Mongalayer uses a structured error system that distinguishes between validation errors, database errors, and authorization errors. All errors extend the ServerError class and can be serialized to JSON for transport over HTTP.
Error types
ServerError
The base error class for all Mongalayer errors. Every error has a type, code, and message.
import { ServerError, ServerErrorType } from "@mongalayer/server";
try {
await layer.execute(action, payload, accessPayload);
} catch (error) {
if (error instanceof ServerError) {
console.log(error.type); // "ValidationError" | "DatabaseError" | "AuthorizationError"
console.log(error.code); // Error-specific code
console.log(error.message); // Human-readable message
console.log(error.toJSON()); // Serializable object
}
}
ValidationError
Thrown when a payload fails schema validation (e.g., invalid filter, malformed document).
import { ServerErrorType, ValidationErrorCode } from "@mongalayer/server";
// error.code === ValidationErrorCode.Unknown
DatabaseError
Thrown when MongoDB returns an error (e.g., duplicate key).
import { DatabaseErrorCode } from "@mongalayer/server";
// error.code === DatabaseErrorCode.DuplicateKey
// error.code === DatabaseErrorCode.Unknown
AuthorizationError
Thrown when an operation is rejected by the access control system.
import { AuthorizationErrorCode } from "@mongalayer/server";
// error.code === AuthorizationErrorCode.UnauthorizedInsert
// error.code === AuthorizationErrorCode.UnauthorizedUpdate
// error.code === AuthorizationErrorCode.Unknown
Handling errors in your HTTP layer
Since Mongalayer does not include an HTTP server, you need to catch errors and map them to HTTP responses:
app.post("/api/mongalayer", async (req, res) => {
try {
// extract action, payload, accessPayload from req
const result = await layer.execute(action, payload, accessPayload);
// return result
} catch (error) {
if (error instanceof ServerError) {
// Send the structured error to the client
res.status(400).json(error.toJSON());
} else {
res.status(500).json({ message: "Internal server error" });
}
}
});
Client-side error handling
The client SDK automatically deserializes ServerError instances from HTTP responses:
import { MongalayerClient, ServerError, MongalayerAPIError } from "@mongalayer/client";
const client = new MongalayerClient("https://.../api/mongalayer");
try {
await client.db("myapp").collection("projects").findOne({ _id: "missing" });
} catch (error) {
if (error instanceof ServerError) {
// Mongalayer error from the server
console.log(error.type, error.code, error.message);
} else if (error instanceof MongalayerAPIError) {
// Non-Mongalayer HTTP error (e.g., 401, 500)
console.log(error.status, error.message);
} else {
// Network error or other unexpected error
console.error("Unexpected error", error);
}
}
Error codes reference
ServerErrorType
| Value | Description |
|---|---|
Validation | Schema or payload validation failed |
Database | MongoDB operation error |
Authorization | Access control rejection |
Unknown | Unclassified error |
ValidationErrorCode
| Code | Description |
|---|---|
UNKNOWN_VALIDATION_ERROR | General validation failure |
DatabaseErrorCode
| Code | Description |
|---|---|
DUPLICATE_KEY | MongoDB duplicate key error (code 11000) |
UNKNOWN_DATABASE_ERROR | Other MongoDB errors |
AuthorizationErrorCode
| Code | Description |
|---|---|
UNAUTHORIZED_INSERT | Insert rejected by access control |
UNAUTHORIZED_UPDATE | Update rejected by access control |
UNKNOWN_AUTHORIZATION_ERROR | Other authorization failures |
Debugging mode
When debugging is enabled, Mongalayer throws the original errors (Zod validation errors, MongoDB driver errors) instead of wrapping them in ServerError. This provides more detailed stack traces during development:
const layer = new Mongalayer(mongoClient, collections, {
debugging: true
});