Error-first callbacks
- Node.js course
- Beginner
- Lesson 80/116
- 5 min
Learn the Node.js error-first callback convention.
Error-first callbacks
Node.js has an established convention for callbacks: the first parameter of the callback is always the error. This is called the error-first callback.
Syntax: function handler(err, data) { if (err) throw err; console.log(data); }. The first parameter err is null when there is no error, or an error object when there is. The second parameter is the actual data. This convention is used across all of Node.js's core APIs.
This pattern offers a standard way to handle errors. Each time the callback fires, you check err first; if it is null you continue, otherwise you throw or handle it.
Check the error
In error-first callbacks, the first thing to do is check the error. With if (err), you handle the error appropriately: throw, log, or report to the user.
A standard check looks like: if (err) { console.error(err); return; }. This prints the error and exits the function; the data is not processed. When there is no error, err is null and data can be used safely.
You repeat this pattern on every call. Node.js's file, network, and timer APIs follow this convention, so checking the error is an integral part of using callbacks.
Practice Error-first simulation
Define a function loadUser(id, cb). If id is 0, call cb(new Error('missing'), null); otherwise call cb(null, { name: 'Ayşe' }). Call it as loadUser(1, (err, user) => { if (err) { console.error(err.message); return; } console.log(user.name); }).
Starter code
// Define loadUser and call it with an error-first callbackSample solution
function loadUser(id, cb) {
if (id === 0) { cb(new Error('missing'), null); return; }
cb(null, { name: 'Ayşe' });
}
loadUser(1, (err, user) => {
if (err) { console.error(err.message); return; }
console.log(user.name);
});Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the first parameter of an error-first callback?
- Data
- A status code
- The callback name
- The error Correct answer
Explanation: the first parameter is err; null means no issue.
2 Error check
function handler(err, data) {
if (____) throw err;
console.log(data);
}
function handler(err, data) {
if (err) throw err;
console.log(data);
}
Explanation: if (err) throws when there is an error, otherwise it continues.
3 Match the error-first parts
| Term | Meaning |
|---|---|
err |
First parameter |
data |
Second parameter |
null |
Value of err when there is no error |
if (err) |
Error check |