Skip to content

Instantly share code, notes, and snippets.

@cadd
Forked from saiumesh535/app.js
Created May 15, 2019 16:40
Show Gist options
  • Save cadd/80d32f948e37e09a89fbcb0d9acc3e3b to your computer and use it in GitHub Desktop.
Save cadd/80d32f948e37e09a89fbcb0d9acc3e3b to your computer and use it in GitHub Desktop.
error handling in express applicaiton
const express = require('express');
const http = require('http');
const app = express();
app.get('/', (req, res) => {
res.send('Hey!!');
});
app.post('/exceptionRoute', async (req, res) => {
const { username } = req.body;
/* since we are not passing username, any operation on undefined will result in error,
any unhandled error/exception in async await will result 😒😒😒
[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future,
promise rejections that are not handled will terminate the Node.js process with a non-zero exit code
*/
const lengthOfSUername = username.length;
res.json({ status: true, length: lengthOfSUername });
});
app.post('/handleException', async (req, res) => {
/* in above route "exceptionRoute", we have seen, since we are not handling excxeption
that would result in nodejs process to break and that's not good thing. to avoid we will use
try and catch πŸ€¦β€β™‚οΈπŸ€¦β€β™‚οΈπŸ€¦β€β™‚οΈ */
try {
const { username } = req.body;
const lengthOfSUername = username.length;
res.json({ status: true, length: lengthOfSUername });
} catch (error) {
res.status(500).send(`something wen't wrong`);
}
});
/* some higher order function ❀❀ */
const handlerException = fn => (req, res, next) => {
fn(req,res).catch((error) => next(error));
};
const someRouteFunction = async (req,res) => {
/* using try-catch is fine but, if you writing large application, and writing
try catch for all routers result in lot of boiler plate code and also you can't centralize all
errors in one place, so let's see how to do that */
/* Now, we will see how to catch errors/exceptions in async await function without try-catch, and also we will
centralize errors while we are at it πŸ˜‰πŸ˜ŽπŸ˜ */
const { username } = req.body;
const lengthOfSUername = username.length;
res.json({ status: true, length: lengthOfSUername });
}
app.post('/handleExceptionGraceFully', handlerException(someRouteFunction));
/* for catching 404 errors */
app.use((req, res) => {
res.status(404).send('404');
})
/* for cathing all errors,
this is default error handler provided by express,
we will use this function to centralize all our errors
*/
app.use((err, req, res, next) => {
/* now here if your error in development then send stack trace to display whole error,
if it's in production then just send error message and log error with some library as winston etc.. */
if(process.env.NODE_ENV === 'production') {
return res.status(500).send(`something wen't wrong`);
}
res.status(500).send(`hey!! we caugth the error πŸ‘πŸ‘, ${err.stack} `);
})
http.createServer(app).listen(3000, () => {
console.log('server is up');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment