Basic Error Handling — Express JS

Tanvir Ahamed
Dec 11, 2023

--

first of all, make a basic express setup.

const express = require('express')
const app = express()

app.get('/', () => {
throw new Error('This was an error')
})

app.listen(3000, ()) => {
console.log('app listening at port 3000')
})

Express has an invisible default error-handling middleware. It has 4 parameters -> err, req, res, next.

app.use((err, req, res, next) => {

})

When a user sends a false URL we can use this error handling system.

// 404 error handler
app.use((err, req, res, next) => {
res.status(404).send('route not found')
})

It is a custom error handling for all of the errors.

app.use((err, req, res, next) => {
if(err.message) {
res.err(err.message)
}else{
res.send('there is an error')
}
})

--

--

Tanvir Ahamed
Tanvir Ahamed

Written by Tanvir Ahamed

0 Followers

Full-stack developer sharing insights on JavaScript, React, Next.js, Node.js, and software development. Passionate about scalable apps & backend architecture.

No responses yet