Jest on promises: triggerUncaughtException(err, true /* fromPromise */) - jestjs

I'm getting this error while running ALL tests (when I the only test directly that load the function involved, there's no error)
node:internal/process/promises:246
triggerUncaughtException(err, true /* fromPromise */);
^
[UnhandledPromiseRejection: 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(). The promise rejected with the reason
"Error: Ha ocurrido un error, por favor intente de nuevo más tarde".] {
code: 'ERR_UNHANDLED_REJECTION'
}
The block of code of the function that is generating the error is like this:
async getMonthRequests(rut, month) {
try {
// some code, in the test I'm testing that it fails
} catch (error) {
return Promise.reject('Ha ocurrido un error, por favor intente de nuevo más tarde');
}
}
Any idea?

Check the host and port of amqp server while creating connection.
amqp://localhost:5672

Related

NestJS - Microservices - Kafka Exception Handling

I'm using NestJS to implement a microservice architecture, I'm using CLIENT app using NestJS,
The client app receives a rest request and sends to Kafka to get the result
try {
const pattern = 'findDoctors';
const payload = body;
const doctors = await lastValueFrom(
this.client.send(pattern, payload).pipe(timeout(50000)),
);
return doctors;
} catch (e) {
console.log(e);
throw new Error(e);
}
And in the microservice side (Hybrid Application for now, will remove the rest apis later)
#MessagePattern('findDoctors')
findDoctors(#Payload() message): any {
return this.doctorService.searchForDoctors(message.value);
}
async searchForDoctors(data): Promise<any[]> {
this.logger.info('Started search for doctors job');
throw 'Not Found';
}
After i throw the exception i get in the logs
node:17720) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received an instance of Object
at Function.from (buffer.js:330:9)
at ServerKafka.assignErrorHeader (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:137:73)
at ServerKafka.sendMessage (C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:119:14)
at C:\Users\Desktop\Projects\node_modules\#nestjs\microservices\server\server-kafka.js:81:31
at C:\Users\Desktop\node_modules\#nestjs\microservices\server\server.js:46:31
at processTicksAndRejections (internal/process/task_queues.js:79:11)
(node:17720) 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: 3)
(node:17720) [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.
and the client side just waits to timeout and never receive an exception response from the micro service
Tried using RpcException but it's the same
Found the answer
used
return new RpcException('not found');
instead of
throw new RpcException('not found')
throwing the exception needs an exception filter to catch it
#Catch(RpcException)
export class ExceptionFilter implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
return throwError(exception.getError());
}
}
and in the client side you can catch the error when using filters and return a normal http exception, or use filters on that too
#Post('/search')
async findAll(#Body() body) {
console.log('Sending kafka msg');
try {
const doctors = await this.doctorService.findDoctors(body);
return doctors;
} catch (e) {
console.log(e)
throw new HttpException({
status: '500',
error: e.message,
}, 500)
}
}

Unhandled Promise Rejection Warning Occured

I want to create Product Categories , so i handle it in productController class database call in productCatService class. I added JS promise to this . now it gives following error.
productCatController.js
module.exports.createProductCat = async (request, response)=> {
let result = await productCatService.createProductCat(productCatData);
if (result) {
responseService.successWithData(response, "Product Category Created");
} else {
responseService.errorWithMessage(response, result);
}
}
productCatService.js
module.exports.createProductCat = (productCatData) => {
let productCat = {
name: productCatData.name,
desc: productCatData.desc,
count:productCatData.count,
status : productCatData.status
};
return new Promise((resolve,reject)=>{
ProductCategory.create(productCat).then(result => {
resolve(true);
}).catch(error => {
reject(false)
})
});
}
Error
(node:18808) UnhandledPromiseRejectionWarning: false
(Use `node --trace-warnings ...` to show where the warning was created)
(node:18808) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a p
romise 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)
(node:18808) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a no
n-zero exit code.
Never use await without try/catch. You don't have to try/catch every await, but somewhere down the call stack there needs to be a try/catch block.
You don't need try/catch here, just return the promise from ProductCategory.create()...
// productCatService.js
module.exports.createProductCat = (productCatData) => ProductCategory.create({
name: productCatData.name,
desc: productCatData.desc,
count: productCatData.count,
status: productCatData.status
});
...but you definitely need try/catch here, as this function is the bottom of the stack for this operation, and it is responsible for signifying overall success or failure to the caller.
// productCatController.js
module.exports.createProductCat = async (request, response) => {
try {
await productCatService.createProductCat(productCatData);
responseService.successWithData(response, "Product Category Created");
} catch (err) {
responseService.errorWithMessage(response, err);
}
}
Also don't use new Promise() for operations that already are promises. Keep using the promise you already have. Wrapping new Promise() around existing promises is a source of useless bloat, and it can introduce subtle bugs. Avoid.

Try to cach UnhandledPromiseRejectionWarning discord.js

i'm trying to catch an discord.js error
This error pops up when internet is off, but i want some clean code instead this messy one...
How can i catch this?
I did really try everything..
code:
(node:11052) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:66:26)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11052) 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 termin
ate the node process on unhandled promise rejection, use the CLI flag `--unhandl
ed-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejecti
ons_mode). (rejection id: 2)
(node:11052) [DEP0018] DeprecationWarning: Unhandled promise rejections are depr
ecated. In the future, promise rejections that are not handled will terminate th
e Node.js process with a non-zero exit code.
i did try this at the very top :
process.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
aswell this one :
client.on('error', error => {
if (error.code === 'ENOTFOUND') {
console.log(no internet!!)
}
});
I also did try this to see where its from, but nothing shows up its still the same
try {
var err = new Error("my error");
Error.stackTraceLimit = infinity;
throw err;
} catch(e) {
console.log("Error stack trace limit: ")
console.log(Error.stackTraceLimit);
}
Error stack trace limit:
10
(node:11008) UnhandledPromiseRejectionWarning: Error: getaddrinfo ENOTFOUND disc
ordapp.com
here is the code i use for now what gives the error.
i just want to catch the error in something like this: (No connection)
const Discord = require('discord.js')
const client = new Discord.Client({ autoReconnect: true });
const opn = require('opn')
const getJSON = require('get-json')
const request = require('request');
const config = require("./config/config.json");
const pushbullet = require("./config/pushbullet.json");
const addons = require("./config/addons.json");
const Registration = require("./config/Reg.json");
client.on('uncaughtException', function (err) {
//console.log('### BIG ONE (%s)', err);
console.log("555")
});
client.login(config.Settings[0].bot_secret_token);
I would try to wrap it with try/catch.
And maybe add the following code to understand better what is happening.
Error.stackTraceLimit = Infinity
Reference:
https://developer.mozilla.org/en-US/docs/Archive/Web/JavaScript/Microsoft_Extensions/Error.stackTraceLimit
Remember to remove it after the problem solved, this is not suitable for production use.
Well i solved it!!
I put this on top and its all solved.
process.on('unhandledRejection', error => {
if (error.code === "ENOTFOUND") { console.log ("No internet connection")}
if (error.code === "ECONNREFUSED") { console.log ("Connection refused")}
//console.log('Unhandled promise rejection:', error.code);
});

`newSession` not found when using local capabilities

I'm facing this error when trying to use BrowserStack local capability:
(node:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) 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:67602) [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:67602) UnhandledPromiseRejectionWarning: UnsupportedOperationError: newSession: Not Found
at parseHttpResponse (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:578:11)
at Executor.execute (/Users/ardo/Documents/workspace/test-browser-stack/node_modules/selenium-webdriver/lib/http.js:489:26)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:67602) 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: 3)
My code is pretty simple:
const webdriver = require('selenium-webdriver');
const browserstack = require('browserstack-local');
const runTestSuite = () => {
const capabilities = {
browserName: 'Chrome',
browser_version: '80.0 beta',
os: 'OS X',
os_version: 'Catalina',
resolution: '1024x768',
'browserstack.user': '<user>',
'browserstack.key': '<key>',
'browserstack.local': true,
'browserstack.localIdentifier': 'ardotest',
// 'browserstack.use_w3c': true,
acceptSslCerts: true,
name: 'Bstack-[Node] Sample Test-OS X Catalina-Chrome 80',
};
// https://www.browserstack.com/question/663
const driver = new webdriver.Builder()
.usingServer('http://localhost:3000') // tried using the IP that I got from Network settings on my machine, it spat out the same error
.withCapabilities(capabilities)
.build();
console.log('quit');
driver.quit();
};
// creates an instance of Local
const bsLocal = new browserstack.Local();
// replace <browserstack-accesskey> with your key. You can also set an environment variable - "BROWSERSTACK_ACCESS_KEY".
const bsLocalArgs = { key: '<browserstack-accesskey>' };
// https://github.com/browserstack/browserstack-local-nodejs/blob/master/lib/Local.js
// starts the Local instance with the required arguments
bsLocal.start(bsLocalArgs, function(err) {
if (err) {
console.error(err);
return;
}
if (!bsLocal.isRunning()) {
return;
}
try {
runTestSuite();
} catch (e) {
console.error(e);
} finally {
// stop the Local instance
bsLocal.stop(function(err) {
if (err) {
console.error(err);
}
console.log('===== BrowserStack tunnel stopped =====');
});
}
});
Versions:
"selenium-webdriver": "^4.0.0-alpha.5",
"browserstack-local": "^1.4.5",
My local environment:
"node": "10.16.3",
"npm": "6.8.0",
macOS 10.14.6
Looking through the code, it's clear that it's trying to hit /session url to create a new session or something. I'm not sure whether I should support /session manually, or I'm just missing something that's really stupid here?
It seems that BrowserStack provides it's own Hub URL for the test executions. You may try changing the hub URL from localhost:3000 to BrowserStacks hub url.
Referring to this code -> .usingServer('http://localhost:3000')
This document has more details: https://www.browserstack.com/local-testing/automate
You just need to make sure to have the same localIdentifier arg in both capabilities AND bsLocalArgs.
That is, both in .withCapabilities(<here>) and new browserstack.Local().start(<here>, ...)

What is process._tickCallback Node.js error

Me and my friend working on project in node.js. We had a error which we don't know what it is. Can you guys explain about it? Here's the error:
at process._tickCallback (internal/process/next_tick.js:188:7)
(node:10758) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwin
g inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
(rejection id: 2335)
P.S: My friend didn't allow me to post code.
This error happens when developers forget adding async error handling via .catch() or try... catch. Compare:
(async function main() {
try {
await Promise.reject();
} catch (err) {
console.error('Rejection handled.');
}
})();
Rejection handled.
(async function main() {
await Promise.reject();
})();
UnhandledPromiseRejectionWarning: ...

Resources