Skip to main content

Error Handling

Error handling is an important aspect of any software development project, and bridge-mongo makes it easy to handle errors that occur while working with the database. Functions in bridge-mongo return an object that includes an error property. To check for errors, you can use the isError function, which checks if the error property is present in the result object.

For example, let's say you are using the Model.findOne(). If no document are found, the result object will include an error property. To handle this error, you can simply check for the error property using isError, and then take appropriate action based on the error.

Here's an example:

ts
import { isError } from 'bridge-mongo';
 
async () => {
const result = await DB.user.findOne({ name: 'Nab' }, { name: 1 });
const result: { error: { status: 404; name: "User not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; name: string; }
 
if (isError(result)) {
console.error('An error occurred:', result.error);
(property) error: { status: 404; name: "User not found"; }
// Handle the error appropriately
} else {
console.log('Document created successfully:', result);
const result: { _id: mongoose.Schema.Types.ObjectId; name: string; }
}
}
ts
import { isError } from 'bridge-mongo';
 
async () => {
const result = await DB.user.findOne({ name: 'Nab' }, { name: 1 });
const result: { error: { status: 404; name: "User not found"; }; } | { _id: mongoose.Schema.Types.ObjectId; name: string; }
 
if (isError(result)) {
console.error('An error occurred:', result.error);
(property) error: { status: 404; name: "User not found"; }
// Handle the error appropriately
} else {
console.log('Document created successfully:', result);
const result: { _id: mongoose.Schema.Types.ObjectId; name: string; }
}
}