Nodejs Netsuite restless Error : (node:1128) UnhandledPromiseRejectionWarning: Unhandled promise rejection - node.js

I am using nodejs npm module netsuite-rest to connect to netsuite rest web services and I am getting this error : UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch bloc
let NetSuiteRestlet = require('netsuite-restlet');
const config = {
account: 'XXXXX',
username: 'XXXXX',
password: 'XXXX',
role: 'FOM PH Sales Manager'
};
const url = 'https://6218235.suitetalk.api.netsuite.com';
const parameters = {
internalid: 1054
};
let ns = new NetSuiteRestlet(config);
// Example using the get function
ns.get(parameters, url).then((out) => { console.log(out) });

It looks like your get request is failing, but is not being handled correctly.
Since you are using promises, you would simply chain on a .catch after the .then to catch the promise rejection.
For example:
ns.get(parameters, URL)
.then((out) => { console.log(out) })
.catch((error) => {
console.log(error) // and/or handle the error some other way
}
See here for more:
How to handle promise rejections: https://flaviocopes.com/javascript-promises-rejection/

Related

Why am I having trouble displaying and deleting in Mongo using Prisma (React app)?

I use Node, Express, React, Mongo and Prisma to import a csv file in the database, display it on the frontend and delete all records in the db. It worked with one record and so I assumed it would work with the rest of the csv file (1000 records). But I get an error:
Invalid `prisma.movie.findMany()` invocation:
Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: RawError { code: "unknown", message: "Command failed (CursorNotFound): cursor id 124425195753416376 not found)" } })
(node:2171) UnhandledPromiseRejectionWarning: Error:
Invalid `prisma.movie.deleteMany()` invocation:
Error occurred during query execution:
ConnectorError(ConnectorError { user_facing_error: None, kind: RawError { code: "unknown", message: "Command failed (CursorNotFound): cursor id 4391617472265441923 not found)" } })
at cb (/Users/nwsursock/Sites/test-algot/backend/node_modules/#prisma/client/runtime/index.js:36378:17)
at runMicrotasks ()
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async exports.deleteRequest (/Users/nwsursock/Sites/test-algot/backend/src/controllers/movie.controller.js:49:3)
(node:2171) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
My code is rather simple. I'm using the Prisma API in REST endpoints.
const { PrismaClient } = require("#prisma/client");
const prisma = new PrismaClient();
exports.createRequest = async (req, res) => {
const movie = req.body.movie;
console.log("============> importing", movie);
const data = {
name: movie.Name,
genre: movie.Genre,
descr: movie.Description,
director: movie.Director,
actors: movie.Actors,
year: movie.Year,
runtime: Number(movie["Runtime (Minutes)"]),
rating: Number(movie.Rating),
votes: Number(movie.Votes),
revenue: Number(movie["Revenue (Millions)"]),
score: Number(movie.Metascore),
};
const result = await prisma.movie.create({ data });
console.log("============> imported", result);
res.status(201).json({ message: "Movie correctly added!" });
};
exports.readRequest = async (req, res) => {
try {
const movies = await prisma.movie.findMany();
res.status(200).json(movies);
} catch (e) {
console.log("======> Error:", e.message);
}
};
exports.deleteRequest = async (req, res) => {
await prisma.movie.deleteMany({});
res.status(202).json({ message: "Table deleted!" });
};
It's a version problem. You have to downgrade to Prisma 2.26. Above, the bug appears. https://github.com/prisma/prisma/issues/8389

Mock fetch in Jest tests throwing “invalid json response” and “Unhandled promise rejection” errors

I’m trying to do unit tests for some of my redux-saga generators and am getting a couple of errors I’m not sure how to resolve. I’m using create-react-app, so my testing suite is Jest and Enzyme.
A basic example:
Setup: src/setupTests.js
import 'jest-enzyme'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
global.fetch = require('jest-fetch-mock')
configure({
adapter: new Adapter(),
automock: false,
collectCoverageFrom: [
'<rootDir>/src/**/*.js',
'!<rootDir>/src/**/*.stories.js',
'!<rootDir>/node_modules/',
'!<rootDir>/src/index.js',
],
coverageThreshold: {
global: {
branches: 90,
functions: 90,
lines: 90,
statements: 90,
},
},
verbose: true,
})
Saga: src/store/sagas/api-saga.js
import { takeEvery, put } from 'redux-saga/effects'
import {
API_ERRORED,
DATA_LOADED,
DATA_REQUESTED,
} from '../constants/action-types'
export function* workerSaga() {
try {
const payload =
yield fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
yield put({
type: DATA_LOADED,
payload,
})
} catch (e) {
yield put({
type: API_ERRORED,
payload: false,
})
}
}
export default function* watcherSaga() {
yield takeEvery(
DATA_REQUESTED,
workerSaga,
)
}
Saga Test: src/store/sagas/api-saga.test.js
import { put, takeEvery } from 'redux-saga/effects'
import watcherSaga, { workerSaga } from './api-saga'
import {
API_ERRORED,
DATA_LOADED,
DATA_REQUESTED,
} from '../constants/action-types'
describe('saga workers', () => {
test('should dispatch action "DATA_LOADED" with result from fetch API',
() => {
const articles = 'Some content'
const mockResponse = {
articles,
}
const generator = workerSaga()
generator.next()
expect(generator.next(mockResponse).value)
.toEqual(
put({
type: DATA_LOADED,
payload: {
articles,
},
})
)
expect(generator.next().done).toBeTruthy()
})
})
The errors I’m receiving:
(node:2009) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
(node:2009) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:2009) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
(node:2009) UnhandledPromiseRejectionWarning: FetchError: invalid json response body at undefined reason: Unexpected end of JSON input
(node:2009) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
I thought introducing jest-fetch-mock would help resolve some of these issues, but it doesn’t seem so. The tests pass, but these errors persist.
What am I missing?
Versions
redux#4.0.4
redux-saga#1.0.5
enzyme#3.10.0
jest#24.7.1
You'll need to set up jest-fetch-mock to return a value:
Something like:
describe('saga workers', () => {
test('should dispatch action "DATA_LOADED" with result from fetch API',
() => {
const articles = 'Some content'
const mockResponse = {
articles,
}
// configure the mockResponse here:
fetch.mockResponse(mockResponse);
const generator = workerSaga()
generator.next()
expect(generator.next().value)
.toEqual(
put({
type: DATA_LOADED,
payload: {
articles,
},
})
)
expect(generator.next().done).toBeTruthy()
})
})
See https://github.com/jefflau/jest-fetch-mock#api

how can i parse a error message that i am getting in nodejs app

I am making an app with reactjs frontend and nodejs backend api for that at someplace i getting error something like this.
But here i want to get only this message email: {message: "This email is already taken", I tried to parse this error using some online turorial but when i try them i get error from backend.
This is the error after using errorparser
(node:14208) UnhandledPromiseRejectionWarning: ReferenceError: errors is not defined
at exports.default (C:/projects/bookworm-practice/bookworm-api/src/utils/parseErrors.js:5:15)
at C:/projects/bookworm-practice/bookworm-api/src/routes/users.js:14:54
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:14208) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:14208) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
this is my parseError function
import _ from 'lodash';
export default function () {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}
this is my user function where i am using parseError
import express from 'express';
import User from '../models/User';
import parseErrors from '../utils/parseErrors';
const router = express.Router();
router.post('/', (req, res) => {
const { email, password } = req.body.user;
const user = new User({ email });
user.setPassword(password);
user.save()
.then(user => res.json({ user: user.toAuthJSON() }))
//.catch(err => res.json({ err })); // this is the default one
.catch(err => res.status(400).json({ errors: parseErrors(err.errors)
//this is after adding parseErrors funtion
}))
})
export default router;
Your parseErrors function did not includes errors as argument
import _ from 'lodash';
export default function (errors) {
const result = {};
_.forEach(errors, (val, key) => {
result[key] = val.message;
});
return result;
}

Nothing happen inside of an async function (send request with easysoap)

I am new in node.js, and I am experimenting things since a few days already.
Today, I have tried to send a XML request to an API, with the use of easysoap-request.
It worked perfectly, but I would have had to create an XML file for each different query, so I tried with easysoap. Here my code:
const EasySoap = require('easysoap');
console.log("test");
(async () => {
const params = {
host : 'https://comeapi.com',
path : '/dir/soap',
wsdl : '/dir/wsdl',
headers: [{
'user-agent': 'Request-Promise',
'Content-Type': 'text/xml',
}]
}
var soapClient = EasySoap(params);
soapClient.call({
method :'one_methode',
attributes: {
xmlns: 'https://someapi.com'
},
params: {
'api' : {
'authentication' : {
'login' : 'mylogin',
'password' : 'mypassword'
},
'params' : {
'another_params' : {
'name' : 'Brian',
}
}
}
}
}).then((callResponse) => {
console.log(callResponse.data); // response data as json
console.log(callResponse.body); // response body
console.log(callResponse.header); //response header
}).catch((err) => {
throw new Error(err);
});
console.log("test2");
});
console.log("test3");
When I'm starting my file with the node command, it's only shows me "test" and "test 3" in the terminal, instead of the response of the API.
I do not understand the problem in my program because I have already used the "(async () => {" function in previous programs, and that rather well worked.
Thanks for you're help. ^^
Edit: I added the missing part in my code and now there is something new. It's an error, and I don't understand it...
(node:10264) UnhandledPromiseRejectionWarning: Error: Error: no wsdl/xml response
at soapClient.call.then.catch (C:\Users\user\Documents\src\script.js:40:15)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:10264) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:10264) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Is this a problem with the .catch() ? Can someone explain me ?
Thanks
Your function is only defined but never called. Call your function at the end of the definition
(async () => {
....
console.log("test2");
})(); // call this function by adding this parenthesis
This is called a IFFY(Immediately-Invoked Function Expression) function in javascript
If you don't want to use a IFFY name your function and call it, like this
const f = async () => {
....
console.log("test2");
}
f()
Your async function needs to be called. Currently you are only declaring a function. To execute it, you need to replace the line before console.log("test3"); by })();

Keep getting the "ConfigError: Missing region in config" error in Node.js no matter what I do

I keep getting the "UnhandledPromiseRejectionWarning: ConfigError: Missing region in config" when trying to make requests to APIs I have set up in Node.js.
I'm new to DynamoDB and after setting up most of my boilerplate code I'm using Postman to test my routes. However I keep getting the same error each time I make a post request. I've checked some solutions on existing threads, namely: Configuring region in Node.js AWS SDK but cannot get it to work.
I am currently developing the app locally and checked the database where the items are being added.
My setup is as follows:
// user_controller.js
const uuid = require('uuid');
const sanitizer = require('validator');
const bcrypt = require('bcryptjs-then');
const AWS = require('aws-sdk');
const config = require('../config/config');
const { signToken, userByEmail, userById } = require('../Helpers/Users');
const isDev = true
Then in my code block I have the following:
// user_controller.js
(...)
if (isDev) {
AWS.config.update(config.aws_local_config);
} else {
AWS.config.update(config.aws_remote_config);
}
const DB = new AWS.DynamoDB.DocumentClient();
const params = {
TableName: config.aws_table_name,
Item: {
userId: await uuid.v1(),
firstName: sanitizer.trim(firstName),
lastName: sanitizer.trim(lastName),
email: sanitizer.normalizeEmail(sanitizer.trim(email)),
password: await bcrypt.hash(password, 8),
level: 'standard',
createdAt: new Date().getTime(),
updatedAt: new Date().getTime(),
},
}
return userByEmail(params.Item.email) // Does the email already exist?
.then(user => { if (user) throw new Error('User with that email exists') })
.then(() => DB.put(params).promise()) // Add the data to the DB
.then(() => userById(params.Item.id)) // Get user data from DB
.then(user => (err, data) => {
console.log("AFTER USER CREATED")
if (err) {
res.send({
success: false,
message: 'Error: Server error'
});
} else {
console.log('data', data);
res.send({
statusCode: 201,
message: 'Success - you are now registered',
data: { token: signToken(params.Item.id), ...user },
});
}
})
(...)
Finally I am importing the config from separate file:
// config.js
module.exports = {
aws_table_name: 'usersTable',
aws_local_config: {
region: 'local',
endpoint: 'http://localhost:8000'
},
aws_remote_config: {}
}
In have already configured the aws-sdk:
AWS Access Key ID [****************foo]:
AWS Secret Access Key [****************bar]:
Default region name [local]:
Default output format [json]:
Here is the output I keep getting:
(node:4568) UnhandledPromiseRejectionWarning: ConfigError: Missing region in config
at Request.VALIDATE_REGION (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:92:45)
at Request.callListeners (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:106:20)
at callNextListener (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/sequential_executor.js:96:12)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:86:9
at finish (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:350:7)
at /Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:368:9
at SharedIniFileCredentials.get (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/credentials.js:127:7)
at getAsyncCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:362:24)
at Config.getCredentials (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/config.js:382:9)
at Request.VALIDATE_CREDENTIALS (/Users/BANGBIZ/Programming/techstars/capexmove/SmartLegalContract/node_modules/aws-sdk/lib/event_listeners.js:81:26)
(node:4568) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
(node:4568) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Like I said, I've tried a lot of variations on this but to no avail. Would love some help, thanks.
I dont know if this helps, but I used none instead of local for the region and it seemed to work for me
AWS.config.update({ region: 'none' })

Resources