Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions absolute-beginners/full-stack/backend/error-handling.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ app.use((err, req, res, next) => {
});
```

:::info Security Tip
Exposing the error message directly to the client can leak sensitive information about the server's internal state. It is safer to only include detailed error information when the application is running in a development environment.

```javascript title="server.js"
res.status(500).json({
success: false,
message: "Internal Server Error",
error: process.env.NODE_ENV === 'development' ? err.message : {}
});
```
:::

## 3. Throwing Custom Errors

Sometimes, the code isn't "broken," but the user did something wrong (like entering the wrong password). In these cases, you can "throw" your own error to trigger the catch block.
Expand Down
26 changes: 26 additions & 0 deletions absolute-beginners/full-stack/backend/express.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,32 @@ npm install -g nodemon
nodemon server.js
```

:::info
Installing packages globally with `-g` is generally discouraged for project-specific tools. It is better to install nodemon as a development dependency to ensure that all developers working on the project use the same version.

```bash
npm install --save-dev nodemon
```

Then, you can add a script to your `package.json`:

```json title="package.json"
{
"scripts": {
"dev": "nodemon server.js"
}
}
```

Now you can start your server with:

```bash
npm run dev
```

This way, everyone on the project will have the same version of nodemon, and you won't run into issues if someone doesn't have it installed globally.
:::

## Practice: The Dynamic Greeter

Let's use **URL Parameters** to greet users by name!
Expand Down
15 changes: 15 additions & 0 deletions absolute-beginners/full-stack/backend/mvc-pattern.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,21 @@ exports.getProfile = async (req, res) => {
};
```

:::info
The `async` controller function lacks error handling. If the database call fails, the promise will reject without being caught, which can lead to unhandled promise rejections. It is best practice to wrap the logic in a `try...catch` block and pass the error to the `next` middleware.

```javascript title="userController.js"
exports.getProfile = async (req, res, next) => {
try {
const userData = await User.findById(req.params.id);
res.json(userData);
Comment on lines +97 to +98
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When fetching a resource by ID, it is a best practice to handle the case where the resource is not found. If User.findById returns null, the controller should return a 404 Not Found status. This provides better feedback to the client than returning a 200 OK with a null body, which is especially important in a tutorial aimed at 'Master' level development.

        const userData = await User.findById(req.params.id);
        if (!userData) {
            return res.status(404).json({ message: "User not found" });
        }
        res.json(userData);

} catch (error) {
next(error);
}
};
```
:::

**3. The Model (`/models/userModel.js`):** The definition of the data.

```javascript title="userModel.js"
Expand Down
14 changes: 14 additions & 0 deletions absolute-beginners/full-stack/backend/nodejs-basics.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,20 @@ fs.readFile('note.txt', 'utf8', (err, data) => {
});
```

:::info Error Handling
In the above example, if `note.txt` does not exist, the `err` object will contain the error details. Throwing an error inside an asynchronous callback will cause the Node.js process to crash. Instead of throwing, you should log the error or handle it gracefully to keep the server running.

```javascript title="readFile.js"
fs.readFile('note.txt', 'utf8', (err, data) => {
if (err) {
console.error("Error reading file:", err);
return;
}
console.log("File content:", data);
});
```
:::

## Practice: The Greeting Machine

1. Create a file named `greet.js`.
Expand Down
10 changes: 5 additions & 5 deletions absolute-beginners/full-stack/backend/routing.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,11 @@ router.get('/all', (req, res) => {
router.get('/:id', (req, res) => {
const bookId = req.params.id;
// In a real app, you'd fetch the book from the database
if (bookId == 1) {
res.json({ id: 1, title: "The Great Gatsby" });
} else if (bookId == 2) {
res.json({ id: 2, title: "To Kill a Mockingbird" });
} else {
if (bookId === "1") {
res.json({ id: 1, title: "The Great Gatsby" });
} else if (bookId === "2") {
res.json({ id: 2, title: "To Kill a Mockingbird" });
} else {
res.status(404).send("Book not found!");
}
});
Expand Down
Loading