express version : 4.15,
node version: 8.1.4
im currently experiencing an odd behavior within my application, I have nested routes and im defining my routes like this
const router = require('express').Router();
const m = require('../modules/index').v1;
router.route('/')
.post(m.create)
.get(m.list)
.all(m.transformer);
router.route('/:id')
.all(m.middlewareById)
.put(m.editById)
.delete(m.deleteById)
.get(m.getById)
.all(m.transformer);
module.exports = router;
Im currently developing m.create API controller, and when and error occurs that is not handled sends me a response of HTML page with error object.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>[object Object]</pre>
</body>
</html>
I want to eliminate this behavior and response with JSON only, but somehow its by passing my defined request handlers, and instead of getting handled at a middle ware that I specify, or the one at app.js
its is being handled somewhere else mysteriously, i've been express user for 3 or more years and this is the first time im facing such behavior.
has something changed in new Express version?
_app.js_
const express = require('express');
const path = require('path');
// const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
...
app.use('/', index);
app.use('/systemadmin', systemAdminRoutes);
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((err, req, res) => {
// next is the last argument in above function
// set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get('env') === 'development' ? err : {};
debug(err); // nothing logs here
debug(err.message);
debug(err.name);
debug(err.errorCode);
debug(err.stack);
// render the error page
res.status(err.status || 500);
res.send({error: err.message}); //this never gets called
});
module.exports = app;
Maybe you ran a linter on your code recently? Your code above you have
app.use((err, req, res) => {
But (which has always been in the case), it MUST have 4 arguments in order to work:
app.use((err, req, res, next) => {
@dougwilson this is insane !
Thanks by the way :)
It did work.
Most helpful comment
Maybe you ran a linter on your code recently? Your code above you have
But (which has always been in the case), it MUST have 4 arguments in order to work: