Last active
January 20, 2018 05:33
-
-
Save xiaoyunyang/c577c4dda835746b1dbc5bb1ae708c57 to your computer and use it in GitHub Desktop.
Error Handling in Node/Express App
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import express from 'express' | |
import path from 'path' | |
import fs from 'fs' | |
const app = express() | |
app.set("port", process.env.PORT || 3001) | |
// Middleware that serves static file ====================================== | |
app.use('/static', (req, res, next) => { | |
const filePath = path.join(__dirname, "static", req.url); | |
res.sendFile(filePath, (err) => { | |
if(err) { | |
next(new Error("Error sending file!")); | |
} | |
}) | |
}) | |
// Error Handler =============================================================== | |
// middleware that logs the error | |
app.use((err, req, res, next) => { | |
console.error(err) | |
next(err) | |
}) | |
// middleware that responds to the 500 error | |
// The 500 error is associated with a requesting a file that does not exist | |
app.use((err, req, res, next) => { | |
res.status(500).send("Internal server error.") | |
}) | |
// middleware that responds to the 404 error | |
// The 404 error is associated with a GET request failure | |
app.use((req, resp) => { | |
resp.status(404).send("Page not found!") | |
}) | |
// launch ====================================================================== | |
// Starts the Express server on port 3001 and logs that it has started | |
app.listen(app.get("port"), () => { | |
console.log(`Express server started at: http://localhost:${app.get("port")}/`); // eslint-disable-line no-console | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You should add all your error-handling middleware to the end of your middleware stack (i.e., add all the error handling code to the end of the app.js file). Although code from app.js is executed sequentially from top to bottom, you want to put your error handler in the end to capture cascaded error from middleware occurring earlier in the stack. You hook up the non-error handling middleware to the error handling middleware via the
next
parameter. If there is no error, the error handling code is not going to be executed.Questions
Suppose our static folder only contains one file: "cat.png".
Which error handling middleware will be executed if you requested the following?
localhost:3001/staticc/cat.png
localhost:3001/static/dog.png
Answers