All quizzesMedium
HTTP Servers & APIs
Preview — 3 of 10 questions
What is the proper way to handle errors in Express?
javascript
const express = require("express");
const app = express();
app.use(express.json());
app.get("/api/users/:id", (req, res, next) => {
try {
const id = req.params.id;
// Validate input
if (!id || isNaN(id)) {
return res.status(400).json({ error: "Invalid user ID" });
}
// Simulate database fetch
const user = getUser(id); // Might throw
if (!user) {
return res.status(404).json({ error: "User not found" });
}
res.json(user);
} catch (error) {
// Pass to error handler middleware
next(error);
}
});
// Error handling middleware (must be last)
app.use((err, req, res, next) => {
console.error("Error:", err.message);
res.status(500).json({ error: "Internal server error" });
});
app.listen(3000);AThrow errors and let them crash the server.
BUse try/catch and send error responses.
CIgnore errors; they fix themselves.
DUse console.log to display errors.
What is the benefit of using async/await in Express routes?
javascript
app.get("/api/users/:id", (req, res) => {
getUser(req.params.id, (err, user) => {
if (err) {
return res.status(500).json({ error: err.message });
}
updateUserLastLogin(user.id, (err) => {
if (err) {
return res.status(500).json({ error: err.message });
}
logActivity(user.id, "viewed", () => {
res.json(user); // Three levels of nesting
});
});
});
});AMakes code faster.
BMakes code cleaner and easier to handle errors.
CAsync/await is not useful in Express.
DOnly works for GET requests.
What are environment variables and why use them?
javascript
# .env
DATABASE_URL=postgresql://localhost/mydb
API_KEY=secret123
NODE_ENV=development
PORT=3000AVariables stored in JavaScript files.
BVariables stored outside code for configuration (database URL, API keys, etc.).
CVariables that change based on user input.
DVariables for environment conditions like temperature.
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.