My code looks like this
app.get('/', function(req, res, next) {
if (id==8) {
res.send('0e');
} else {
next();
}
});
app.use(function(err, req, res, next){
res.send(500, '<h1>Oops! what happened?</h1>');
});
So. the next() function is called the message Ooops! what happened should appear on screen but instead a message ' Cannot GET / ' appears
You can use node.js built in uncaught exception, just put this code inside your server.js
process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
//you can also email this error
});
or follow this link
http://masashi-k.blogspot.com/2012/12/express3-global-error-handling-domain.html
Error handlers are only called if next() was called with an Error object.
So to trigger your error handler you'd have to do:
app.get('/', function(req, res, next) {
if (id==8) {
res.send('0e');
} else {
next(new Error('Fake error occurred'));
}
});
app.use(function(err, req, res, next){
res.send(500, '<h1>Oops! what happened?</h1>');
});
Related
I have a basic Express app which has a few routes.
One is as such:
router.post('/upload', (req, res) => {
let audioFile = req.files.audioFile;
const file = __dirname + '/../' + req.body.uploadLocation + audioFile.name;
mp3.mv(file, function(err) { // <--- HERE
if (err) {
return res.status(500).send(err);
}
res.send('File uploaded!');
});
});
Now, if you would try to upload a file to this route you would get a 500 and that's it. The highlighted line is a result of me changing variable name. Is there any way to get it so that it prints out the actual error? I am tripped up by this so often and it would make it an awful lot quicker if the terminal output just told me the normal JS error like it does on the browser or when I'm running node normally.
In Express there is middleware to handle errors. In the a base setup of express you'll find:
// error handler
app.use(function(err, req, res, next) {
...
// render the error page
res.status(err.status || 500);
res.json({ error: err });
});
Just add a console.error there:
// error handler
app.use(function(err, req, res, next) {
console.error(err.stack); // <- HERE
...
// render the error page
res.status(err.status || 500);
res.json({ error: err });
});
I want to create a function that return a http.Server and
Serve the text of the file testText.txt in the body of the HTTP response
when a GET request is made to the '/' route.
Parse the request for a "paragraphs" parameter.
That parameter must be an integer and represent the number of
paragraph you want to receive starting from the beginning of the test text.
Return the appropriate content in the body of the response.
If any error happens, return a 500 error.
If the provided route is not known, return a 404 error.
here is what i have so far
function makeServer() {
return http.createServer(function(req, res){
if(req.url === '/'){
fs.readFile('testText.txt', function(err , para){
console.log("Data", para);
res.end();
});
console.log("The end");
}
}
I would expect to do something like this,
var express = require('express');
var app = express();
//Handle 404 here
app.use(function (req, res, next) {
res.status(404).send({
message: "Page Not Found"
})
});
Inject the GET request to your default route
app.get('/', (req, res) => {
// **modify your existing code here**
fs.readFile('testText.txt', (e, para) => {
if (e) {
res.status(500).send({
message: "Something went wrong"
})
}
res.send(para);
});
});
app.listen(5555);
As you have mentioned in your question use that err object inside the function such as below:
function makeServer() {
return http.createServer(function(req, res){
if(req.url === '/'){
fs.readFile('testText.txt', function(err , para){
if (err) {
res.status(500).send({
message: "Something went wrong"
})
// error handling
} else {
console.log("Data", para);
res.end();
}
});
console.log("The end");
}
}
Firstly, Welcome to the node world...
1) Work with file in res
Please refer this answer. It will help you.
2) Error code 500 if any error
res.status(500).json({success: 0, error 'Something went wrong'});
3) For handle 404 if route not matched
var createError = require('http-errors');
//Install via this command-> npm i http-errors --save
app.use(function (req, res, next) {
next(createError(404));
});
I am trying to write a middleware to handle errors. But I cannot figure out how to send the correct format to my frontend. Below I am going to list all of my attempts in hopes of helping you help me.
Attempt 1
app.use(function(err, req, res, next) {
const formatted = err;
res.send(formatted)
});
result in postman
{ "code": 422 }
Attempt 2
app.use(function(err, req, res, next) {
const formatted = `${err}`;
res.send(formatted)
});
result (postman)
Error: Request returned error code: 422 and body: {"status":422,"title":"The display name: build_id has already been used on this product.","type":"https://developer.bigcommerce.com/api#api-status-codes","errors":{"display_name":"The display name: build_id has already been used on this product."}}
That is the data i want but i need it in json
Question Why is there more data revealed after string interpolation? How can i format it to json?
You're probably looking for res.json(err) if I had to guess?
https://expressjs.com/en/api.html#res.json
EDIT: Full example:
app.use(function(err, req, res, next) {
if (err) res.json(err)
});
You can do it in this way
app.use(function(err, req, res, next) {
if (err) {
res.json({
status: "error",
error: `${err}` // <-- edited
});
} else {
next();
}
});
I am using passport.js for my node app. In the Custom Callback section I found the following code(lets say it Code A):
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
})(req, res, next);
});
My question is I am not able to understand passing (req, res, next) at the end. How the following code(lets say it Code B):
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err); }
if (!user) { return res.redirect('/login'); }
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/users/' + user.username);
});
});
});
How Code B is different from Code A ?
If I simplify Code A then it will be like :
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(..){..})(req, res, next);
});
Further
passport.authenticate(..)(req, res, next);
which means expression like
function(..)(req,res, next)
My Question is more about understanding the syntax
function(..)(parameters)
authenticate() function is structured like this:
module.exports = function authenticate(passport, name, options, callback) {
// ...
return function authenticate(req, res, next) {
// ...
strategy.success = function(user, info) {
if (callback) {
return callback(null, user, info);
}
}
// ...
})
};
So it takes two series of parameters:
The first one (in your case 'local' and the callback function) is used to tell passport to authenticate you, and how to do it;
The second handles the function to control your app with req, res and next parameters.
Hope it helps you to understand!
In ExpressJS app final app.use which is using for error handling
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log('as',typeof err);
// res.render('error1', {
// message: err.message,
// error: {}
// });
res.json(err.message)
});
When I log err it print as {} ,but when I log err.message it show string like 'obj is not defined'. Why this happens and how I can see all the keys of err object like message .
app.use(function(err, req, res, next) {
if(err){
res.json(err)
}
else{
//err is {}
}
});
If it is not error, then the err will be null.