Getting error: Error: Can't set headers after they are sent - node.js

I am following a course from Wesbos on Node.js, and I created a /add GET route that uses the addStore controller:
index.js:
const express = require('express')
const router = express.Router()
const storeController = require('../controllers/storeController')
const { catchErrors } = require('../handlers/errorHandlers')
router.get('/', catchErrors(storeController.getStores))
router.get('/stores', catchErrors(storeController.getStores))
router.get('/add', catchErrors(storeController.addStore))
router.post('/add', catchErrors(storeController.createStore))
router.post('/add/:id', catchErrors(storeController.updateStore))
router.get('/stores/:id/edit', catchErrors(storeController.editStore))
module.exports = router
storeController.js:
exports.addStore = (req, res) => {
res.render('editStore', { title: 'add store'})
}
But when i go to the add route i get the error:
Error: Can't set headers after they are sent.
Any ideas what is wrong?
Here is the editStore and storeform view:
editStore:
extends layout
include mixins/_storeForm
block content
.inner
h2= title
+storeForm(store)
storeForm:
mixin storeForm(store = {})
form(action=`/add/${store._id || ''}` method="POST" class="card")
label(for="name") Name
input(type="text" name="name" value=store.name)
label(for="description") Description
textarea(name="description")= store.description
- const choices = ['wifi','Open-late','Family Friendly', 'vegetarian','licensced']
- const tags = store.tags || []
ul.tags
each choice in choices
.tag.tag__choice
input(type="checkbox" id=choice value=choice name="tags" checked=(tags.includes(choice)))
label(for=choice) #{choice}
input(type="submit" value="Save" class="button")
catchErrors:
/*
Catch Errors Handler
With async/await, you need some way to catch errors
Instead of using try{} catch(e) {} in each controller, we wrap the function in
catchErrors(), catch any errors they throw, and pass it along to our express middleware with next()
*/
exports.catchErrors = (fn) => {
return function(req, res, next) {
return fn(req, res, next).catch(next);
};
};
/*
Not Found Error Handler
If we hit a route that is not found, we mark it as 404 and pass it along to the next error handler to display
*/
exports.notFound = (req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
};
/*
MongoDB Validation Error Handler
Detect if there are mongodb validation errors that we can nicely show via flash messages
*/
exports.flashValidationErrors = (err, req, res, next) => {
if (!err.errors) return next(err);
// validation errors look like
const errorKeys = Object.keys(err.errors);
errorKeys.forEach(key => req.flash('error', err.errors[key].message));
res.redirect('back');
};
/*
Development Error Handler
In development we show good error messages so if we hit a syntax error or any other previously un-handled error, we can show good info on what happened
*/
exports.developmentErrors = (err, req, res, next) => {
err.stack = err.stack || '';
const errorDetails = {
message: err.message,
status: err.status,
stackHighlighted: err.stack.replace(/[a-z_-\d]+.js:\d+:\d+/gi, '<mark>$&</mark>')
};
res.status(err.status || 500);
res.format({
// Based on the `Accept` http header
'text/html': () => {
res.render('error', errorDetails);
}, // Form Submit, Reload the page
'application/json': () => res.json(errorDetails) // Ajax call, send JSON back
});
};
/*
Production Error Handler
No stacktraces are leaked to user
*/
exports.productionErrors = (err, req, res, next) => {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
};
Link to my repo: https://github.com/GiorgioMartini/learnnode/tree/master/maketogether

Related

Node js Error Handler Doesnt get exact error message from Controller Express/Mongoose

I a trying to implement a rest API for our project then I go for node js and express. I have built all the models and controllers. I faced an issue while trying to handle an error. Errorhandler function doesn't receive all the properties of error that caught in try/catch block. I can not read its name in a handler but I can use its name in the controller. Could you please help me?
const errorHandler = (err, req, res, next) => {
console.log(`Error in method:${req.method}: ${err.stack}`.bgRed);
let error = { ...err };
console.log(`Error handler: ${err.name}`);
res.status(error.statusCode || 500).json({
success: false,
data: error.message || 'Server Error',
});
};
module.exports = errorHandler;
controller
const mongoose = require('mongoose');
const Product = require('../models/Product');
const ErrorResponse = require('../utils/error');
const routeName = 'PRODUCT';
// #desc getting single product via id
// #route GET api/v1/products
// #acces public
exports.getProdcut = async (req, res, next) => {
try {
const product = await Product.findById(req.params.id);
if (!product) {
return next(
new ErrorResponse(`Product not found with id:${req.params.id}`, 404)
);
}
res.status(200).json({
success: true,
data: product,
});
} catch (err) {
console.log(err.name);
console.log('ERRO APPEND');
next(new ErrorResponse(`Product not found with id:${req.params.id}`, 404));
}
};
Assuming that errorHandler is part of your middleware that is somewhere after getProdcut, you can try just throwing the error and Express will automatically detect that for you, because error handling middleware such as yours accepts 4 parameters. So the following would work:
const getProdcut = async (req, res, next) => {
try {
// ...
} catch (err) {
throw err;
}
};
const errorHandler = (err, req, res, next) => {
if (err) {
console.log('hello from the error middleware');
console.log(err.name);
}
else {
// next() or some other logic here
}
}
app.use('/yourRoute', getProdcut, errorHandler);
And inside of your errorHandler you should have access to the error object.
Error-handling middleware always takes four arguments. You must provide four arguments to identify it as an error-handling middleware function. Even if you don’t need to use the next object, you must specify it to maintain the signature. Otherwise, the next object will be interpreted as regular middleware and will fail to handle errors.
https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling

How to pass and return data in the next middleware in NodeJs

I am trying to pass data from one middleware to another. The data is then returned to the client in the next middleware. I, however, am unable to catch it in the send.call.
How can I catch the data and send it?
Thank you all in advance.
const myPreMiddleware = async (req, res, next) => {
req.myData = myData;
next();
};
const myPostMiddleware = (req, res, next) => {
let send = res.send;
res.send = async function (body) {
send.call(this, req.myData); // The data i NOT accessible here
};
console.log("req.myData : " + JSON.stringify(req.myData)); // The data is accessible here
next();
};
app.use(myPreMiddleware);
app.use(myPostMiddleware);
Try pass the variable that you want to pass to the next() callback
here some example that will hopefully help
function notFound(req, res, next) {
res.status(404);
const error = new Error(`Not Found - ${req.originalUrl}`);
next(error);
}
function errorHandler(err, req, res, next) {
const statusCode = res.statusCode !== 200 ? res.statusCode : 500;
res.status(statusCode);
res.json({
message: err.message
});
}
app.use(notFound);
app.use(errorHandler);

ValidationError not caught by express error handler

In my mongoose schema, I have a field type that is required. I am using a custom error handler in express defined as
const notFound = (req, res, next) => {
const error = new Error(`Not found-${req.originalUrl}`);
res.status(404);
next(error);
};
const errorHandler = (err, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: err.message,
stack: process.env.NODE_ENV === 'production' ? null : err.stack,
});
};
and use the error handlers at the bottom of my server.js file as
app.use(notFound);
app.use(errorHandler);
However, when I try to test the route that posts an entry using Postman, the request will be stuck and no response is sent back, and in the terminal there is an error saying that UnhandledPromiseRejectionWarning: ValidationError: ...
My question is: shouldn't my custom error handler catch the error?
Make sure that you're forwarding the error wherever you're performing your mongoose action. There you should be able to forward that to your middleware.
For example you can try something like this:
example.findById(req.id, async function(err, foundRecord){
if(err) {
next(err);
} else {
....
}
});
Let me know if that works.
You can try with this simple HttpError:
Create HttpError.js:
class HttpError extends Error {
constructor(statusCode, message = 'Internal Server Error') {
super(message);
this.statusCode = statusCode;
this.isSuccess = false;
this.isError = true;
this.errorMessage = message;
this.data = null;
}
}
module.exports.HttpError = HttpError;
You can create for an example: NotFoundError extends HttpError :
const { HttpError } = require('../HttpError');
class NotFoundError extends HttpError {
constructor(message = 'Not Found') {
super(404, message);
}
}
module.exports.NotFoundError = NotFoundError;
Now, in your app.js, you can handle error like this code below:
// handle notFoundError
app.use((req, res, next) => { throw new NotFoundError() });
// handle unexpectedly error or another error
app.use((error, req, res, next) => {
res.status(error.statusCode || 500).send(error);
})
If you want to look at the tutorial, for mys, but use the indonesian language ("But you don't have to listen, just look at the concept"), you can check it out here:
Handle Express Error: https://www.youtube.com/watch?v=GwS6KJmO9w8&list=PLREvIK3N7Ga6F669gbDCDMwrn37Uq32-O&index=13
Handle HttpError: https://www.youtube.com/watch?v=VoorNGvDypE&list=PLREvIK3N7Ga6F669gbDCDMwrn37Uq32-O&index=14
Or for example code, you can check it out on this github repo: https://github.com/12bedeveloper/basic-express
Keep learn.

Is there a way to test error handling in ExpressJS with Mocha when using a custom error handler?

Test
it('should fail trying to GET bookmarks with false user id',async () => {
try {
const response = await request(app)
.get(baseApiUrlUnderTest + 'false_user_id/bookmarks')
.set('Authorization', bearerToken);
} catch (e) {
console.log(e); //it doesn't reach this point
expect(e.httpStatus).to.equal(HttpStatus.UNAUTHORIZED);
}
});
The relevant part of the method under test:
/* GET bookmark of user */
personalBookmarksRouter.get('/', keycloak.protect(), wrapAsync(async (request, response) => {
userIdTokenValidator.validateUserIdInToken(request);
...
}));
where wrapAsync makes sure the error is passed to the custom error handler:
let wrapAsync = function (fn) {
return function(req, res, next) {
// Make sure to `.catch()` any errors and pass them along to the `next()`
// middleware in the chain, in this case the error handler.
fn(req, res, next).catch(next);
};
}
The validateUserIdInToken method which causes the method under test to throw an exception:
const AppError = require('../models/error');
const HttpStatus = require('http-status-codes');
let validateUserIdInToken = function (request) {
const userId = request.kauth.grant.access_token.content.sub;
if ( userId !== request.params.userId ) {
throw new AppError(HttpStatus.UNAUTHORIZED, 'Unauthorized', ['the userId does not match the subject in the access token']);
}
}
module.exports.validateUserIdInToken = validateUserIdInToken;
and the custom error handler in the root middleware:
app.use(function(err, req, res, next) {
if (res.headersSent) {
return next(err)
}
if(err instanceof AppError) { //execution lands here as expected and the test stops...
res.status(err.httpStatus);
return res.send(err);
} else {
res.status(err.status || HttpStatus.INTERNAL_SERVER_ERROR);
res.send({
message: err.message,
error: {}
});
}
});
I think you may be approaching this incorrectly. Invalid auth should not raise errors in the app - it's not an error really, is a validation issue.
If the auth fails, simply send the relevant http error code - 401 back to the client.
res.send(HttpStatus.UNAUTHORIZED, 'a message if you want'); // 401
In your route handler:
personalBookmarksRouter.get('/', keycloak.protect(), wrapAsync(async (request, response) => {
const userId = request.kauth.grant.access_token.content.sub;
if ( userId !== request.params.userId ) {
return response.send(HttpStatus.UNAUTHORIZED);
}
...
}));
In your test, check the for status 401:
chai.request(server)
.get('/false_user_id/bookmarks')
.end((err, result) => {
if (err) {
return callback(err);
}
result.should.have.status(401);
});
Thanks to #laggingreflex's comment I missed debugging that the response actually returned with the expected status and error message
The adjusted test case now looks like this:
it('should fail trying to GET bookmarks with false user id',async () => {
const response = await request(app)
.get(baseApiUrlUnderTest + 'false_user_id/bookmarks')
.set('Authorization', bearerToken);
expect(response.status).to.equal(HttpStatus.UNAUTHORIZED);
});

Can't set headers after they are sent : multiple middleware executions concurency

In my main express.js config file, I use two custom error middleware functions:
const error = require('../middlewares/error');
// catch 404 and forward to error handler
app.use(error.notFound);
// if error is not an instanceOf APIError, convert it.
app.use(error.converter);
I use boom to unify error messages. this is my error middleware:
module.exports = {
/**
* Error responder. Send stacktrace only during development
* #public
*/
responder: (err, req, res, next) => {
res.status(err.output.payload.statusCode);
res.json(err.output.payload);
res.end();
},
/**
* If error is not a Boom error, convert it.
* #public
*/
converter: (err, req, res, next) => {
if (env !== 'development') {
delete err.stack;
}
if (err.isBoom) {
return module.exports.responder(err, req, res);
}
if (err.name === 'MongoError' && err.code === 11000) {
const boomedError = boom.conflict('This email already exists');
boomedError.output.payload.stack = err ? err.stack : undefined;
return module.exports.responder(boomedError, req, res);
}
const boomedError = boom.boomify(err, { statusCode: 422 });
return module.exports.responder(boomedError, req, res);
},
/**
* Catch 404 and forward to error responder
* #public
*/
notFound: (req, res) => {
const err = boom.notFound('Not Found');
return module.exports.responder(err, req, res);
},
};
My problem is, when I make a "register" action with an existing email, the responder() is executed three times. One for my boom.conflict error, but then also one for "not found". (even though I've done res.end().
This is the register logic:
exports.register = async (req, res, next) => {
try {
validationResult(req).throw();
const user = new User(req.body);
const token = generateTokenResponse(user, user.token());
const userTransformed = user.transform();
user.tokens.push({ kind: 'jwt', token });
user.activationId = uuidv1();
await user.save();
res.status(httpStatus.CREATED);
sendValidationEmail(user.activationId);
return res.json({ user: userTransformed });
} catch (err) {
return next(converter(err, req, res, next));
}
};
user.save() triggers this by the way:
userSchema.pre('save', async function save(next) {
try {
if (!this.isModified('password')) return next();
const rounds = env === 'test' ? 1 : 10;
const hash = await bcrypt.hash(this.password, rounds);
this.password = hash;
return next();
} catch (err) {
return next(converter(err));
}
});
Calling res.end() just tells the response stream that you're done sending data. You don't need that in this case because calling res.json() will do it for you.
However, that isn't the same as telling Express that you're done with handling the request. Just because you've sent a response doesn't necessarily mean you've no work left to do.
The way you tell Express that you've finished is by not calling next(). Express assumes you've finished by default and will only continue executing the middleware/routing chain if you call next().
So this line:
return next(converter(err, req, res, next));
should just be:
converter(err, req, res, next);
Likewise your other call to converter() shouldn't be calling next() either.

Resources