error: invalid input syntax for integer: "NaN" when postgres returns error
Hi man, thanks for node-postgres. Today i'm facing an error i don't know how to solve. Pay attention.
console throws this when i try to insert or update a row in the database.
(node:1782) UnhandledPromiseRejectionWarning: error: invalid input syntax for integer: "NaN"
at Parser.parseErrorMessage (/Users/(user)/Desktop/app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/Users/(user)/Desktop/app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/Users/(user)/Desktop/app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.
But, the thing is that when i try to insert a new row it does and also updates the row but throws the error above and it doesn't return any result in the query. I tried all the ways to solve this but i can't figure out how to..
can you build a self-contained code example you can put in the issue that exercises the problem? It's hard to identify where the problem is from just a stack trace.
Sorry about that. Heres my code, I'm using express and some other libraries to handle data.
const { Pool } = require("pg");
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
});
router.patch("/:id", verifyToken, async (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
try {
let postId = parseInt(id);
if (postId < 0)
res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
//Validate post data
const { error } = validatePostData({
title,
content,
});
//Is there and error? Let the user know it.
if (error)
res.status(400).json(utils.generateError(error.details[0].message));
const slug = await utils.generateSlug(title);
const summary = await utils.extractSummary(content, 240);
const foundImage = await content.match(/!\[.*?\]\((.*?)\)/);
let image = "";
if (foundImage) image = foundImage[1];
const result = await pool.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
);
if (result) res.json(result.rows[0]);
} catch (e) {
console.log(e);
res.json(utils.generateError("Something went wrong, try again."));
}
});
You need to add a return ... on the error handling line:
// Missing "return":
return res.status(400).json(utils.generateError(error.details[0].message));
Otherwise the rest of the code will keep executing and run the UPDATE even though the validation failed which is what's likely happening if the input is bad.
Out of the box express (that is express right?) does not handle async request handlers. You need to use a wrapper to convert the async function into one that invokes next(err) if it fails. Something like:
router.patch("/:id", verifyToken, (req, res, next) => {
Promise.resolve()
.then(async () => {
/* your code goes here */
})
.catch(next); // have any rejected promises go here
});
Otherwise nothing is catching the Promise rejection for the query execution and it will bubble up to the UnhandledPromiseRejectionWarning.
Did what you told me and i got the same error then made this changes.
router.patch("/:id", verifyToken, (req, res) => {
const { id } = req.params;
const { title, content, categories } = req.body;
const authorId = parseInt(req.user.id);
...
pool
.query(
"UPDATE posts SET title=$1, slug=$2, summary=$3, content=$4, image=$5, author=$6, categories=$7 WHERE id=$8",
[title, slug, summary, content, image, authorId, categories, postId]
)
.then((result) => {
if (result) return res.json(result.rows[0]);
})
.catch((err) => {
return res.json(
utils.generateError("Something went wrong, try again.")
);
});
});
But i'm still getting the same error. I'm getting crazy dude.
if the error says invalid syntax for NaN than one of the numbers in your parameters (authorId or postId most likely) is nan. Check them for Number.isNaN(authorId) for example
Nothing. Verified the vars and they are ok. created a new table in db with same fields and nothing. I don't really know what could be the problem.
@ederavilaprado Can you post the whole request handler?
This is the main file
const express = require("express");
const routes = require("./routes/posts");
const app = express();
const port = process.env.PORT;
app.use(express.json());
app.use("/api/posts", routes);
app.listen(port, () => console.log(`Up and running on port ${port}...`));
The routes file code is in the previous comments.
The verifytoken middleware
const jwt = require("jsonwebtoken");
const utils = require("../utils");
module.exports = function (req, res, next) {
const token = req.header("some-token");
if (!token) return res.json(utils.generateError("You need an access token to make requests"));
try {
const verified = jwt.verify(token, "mysecretkey");
req.user = verified;
next();
} catch (e) {
return res.json(utils.generateError("Invalid Token"));
}
};
At a min you need to add the return statements on early error conditions and have your async request handler translate to a vanilla express (req, res ,next) callback interface.
Also, add a console.log(...) to see what value you're getting for postId, the value returned by parseInt(...) would be NaN for empty string or undefined.
let postId = parseInt(id);
console.log('id=%s postId=%s', id, postId); // <= Add this
if (postId < 0)
// Add a return:
return res.json(
utils.generateError("Something went wrong, try to reload the page.")
);
I've already did all that and i'm still getting this error. values of postId and authorId return false to Number.isNaN added a return statement to each error condition and nothing seems to work.
Then post the entire updated request handler, i.e. with the updates for returning errors, logging. Everything.
also if you haven't seen it this guide is how I like to use async/await with express to avoid having to use promise.then.catch stuff
you should check your get request, i was also getting the same error "undefined" precisely in my case for my reference id. The catch is you should get in first instance that perticular id then only you can do update or whatever. Hope you have got the answer