Skip to content

Instantly share code, notes, and snippets.

@xiaoyunyang
Last active January 20, 2018 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaoyunyang/c577c4dda835746b1dbc5bb1ae708c57 to your computer and use it in GitHub Desktop.
Save xiaoyunyang/c577c4dda835746b1dbc5bb1ae708c57 to your computer and use it in GitHub Desktop.
Error Handling in Node/Express App
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
})
@xiaoyunyang
Copy link
Author

xiaoyunyang commented Jan 20, 2018

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?

  1. localhost:3001/staticc/cat.png
  2. localhost:3001/static/dog.png

Answers

  1. 404 - page not found
  2. 500 - internal server error

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment