JS runtime errors in Express - javascript

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 });
});

Related

Creating node server and setting error handlers in node js

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));
});

NodeJs express error middleware parsing

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();
}
});

err is blank but err.message exists on expressJS

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.

Failed to decode param in express

Whenever something like this:
http://localhost:3000/asdd%Asd is typed in (obviously not a route) I get Failed to decode param. How would I catch this error and redirect to a 404 using a route?
Error middleware:
app.use(function(req, res, next) {
var err = new Error('Not Found');
//err.status = 404;
res.redirect('/404');
next(err);
});
package JSON:
"engineStrict": true,
"engines": {
"node": "7.7.4",
"npm": "3.10.10"
},
You have a missing argument in the function signature for your error handler. The first argument is err (the error received). Try something like this:
app.use(function(err, req, res, next) {
res.redirect('/404');
next(err); // <- I don't know enough about ExpressJS to know if this is actually needed. :-D
});

Node.js express next error handler

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>');
});

Categories