Error Handling on yEnc in nodejs - javascript

I am using the yEnc module with Node.
I have been trying to work out how to carry out error handling as the module has no token for an err. How would I perform error handling?
The code I have is as follows:
exports.emailSNSclient = SNSClient(function(err, message) {
var payload = JSON.parse(yEnc.decode(message.Message));
logger.info(payload);
I am unsure if try catch would work because I have been led to believe it doesn't work too well with node.
What is the correct way to do this?
Thanks

Try/catch works fine in this case, as yEnc.decode() is a synchronous operation. The only time try/catch is not suitable is when attempting to catch errors from asynchronous operations.
The following will work fine:
exports.emailSNSclient = SNSClient(function(err, message) {
try {
var payload = JSON.parse(yEnc.decode(message.Message));
logger.info(payload);
} catch(e) {
console.log(e)
}
}

Related

Uncaught (in promise) Error: invalid address

how to fix this error when i call a smart contract function?
Uncaught (in promise) Error: invalid address (argument="address", value={"from":"0xaD1D30B476C195C23ef4CC9b7A3c53E7423B7690"}, code=INVALID_ARGUMENT, version=address/5.0.5) (argument="index", value={"from":"0xaD1D30B476C195C23ef4CC9b7A3c53E7423B7690"}, code=INVALID_ARGUMENT, version=abi/5.0.7)
it's my code:
enter: async function() {
App.contracts["MyContract"].deployed().then(async(instance) =>{
var a = web3.eth.getAccounts();
let ticketsForPlayers = await instance.getTicketsForPlayers({from: App.account});
console.log(ticketsForPlayers);
});
}
The Problem
The error shows that you didn't set the address property correctly, it's may be the issue with your solidity implementation and it's not related to javascript snippet, as mentioned in the comments, you can ask about it on related sites, but there are some points with the above snippet that may help you.
you are mixing two different implementations in enter method to handle a promise which is clearly incorrect and leads to the issues.
The Points
use async/await with try/catch block. more on MDN documentation:
enter: async function () {
try {
const instance = await App.contracts["MyContract"].deployed()
const properNameForVariable = web3.eth.getAccounts();
const ticketsForPlayers = await instance.getTicketsForPlayers({from: App.account})
console.log(ticketsForPlayers)
} catch (error) {
// do a proper action on failure cases
}
}
Now, if there are errors in your async actions, it catches by catch block, you may also use console.error(error) or console.warn(error) in the catch block to see the exception and stack traces.
Note: using this approach with try/catch will ensure the application continues to work even after exceptions and errors.
using an old version of web3 for a tutorial web3#0.20.6 and Firefox 100.0.1
this was what I added to react to get resolve the error
web3.eth.defaultAccount = web3.eth.accounts[0]

Unable to print error message from function call

I am not a JavaScript guy (can only write simple JS function), I am trying to debug a code with the JS where my backed system is passing the correct values but I am getting an error while processing the code on the UI. Here is the JS code
this.session.onvalidatemerchant = function (event) {
this.performAuthorizeMerchantRequest(event.validationURL)
.then(function (merchantSession) {
this.session.completeMerchantValidation(merchantSession);
alert("jdshhdjhjdhh");
}.bind(this))
.catch(this.showPaymentError.bind(this));
}.bind(this);
Here is the error handling function
showPaymentError: function () {
//showing a message on the UI
}
I have already verified the data being passed from my backed service is correct, I don't see the following alter alert("jdshhdjhjdhh");. There seems to be issue with the completeMerchantValidation method but I am not sure what is the root cause for failure.I tried to change my error message with something like this
showPaymentError: function (e) {
console.log("*****111"+e)
}
but getitng the following output in the console *****111TypeError: Type error. Is there a way I can print the error from the completeMerchantValidation. Even tried to add try and catch around that method call but getting js compilation error
Try this. the try catch will handle the potential error which come from performAuthorizeMerchantRequest or completeMerchantValidation.
this.session.onvalidatemerchant = async ({ validationURL }) => {
try {
const merchantSession = await this.performAuthorizeMerchantRequest(validationURL)
this.session.completeMerchantValidation(merchantSession)
alert('jdshhdjhjdhh')
} catch (error) {
console.error('Oh oh, an error happened', error)
this.showPaymentError(error);
}
}
The root cause is a TypeError that is being thrown at some point in the Promise's lifecycle.
Given that console.log("*****111"+e) prints *****111TypeError: Type error, we are dealing with a TypeError.
Unfortunately "Type error" isn't the most useful debugging data :(
Maybe try printing the stacktrace?
https://developer.mozilla.org/en-US/docs/Web/API/Console/trace

Is there an ideal way to catch exceptions when using the Async library in Node.js

We use AWS Lambda for the backend of our mobile application. I just realized that our uncaught exceptions were not being logged correctly so we could be alerted to them. I realize that we could use something like this
process.on('uncaughtException', (err) => {
console.log(...)
process.exit(1) //mandatory (as per the Node docs)
})
This has a lot of problems though as I do not believe we could push the error into our SNS log stream. Ideally, we'd like to put a try catch block around some of our main processing code, but this does not work as its getting called asynchronously and it does not get caught
async.waterfall([
async.apply(verifyCacheIsReady, request_data),
async.apply(verifyRequestAndGetUser, request_data),
async.apply(logSession, request_data)],
function (command_callback)
{
},
function(err)
{
}
I realize I could try catch in all of this functions, but this is a simplified version. Is there a good way to catch something that happens in this block of code?

Javascript - Where exactly to place try - catch?

Try catch is used to catch errors and report to user. all said and fine. But where exactly one has to put the try-catch. Or What exactly has to go inside try catch on a usual basis.
Most importantly, is it absolutely a good coding practice to have a try catch block?
I think it is good practce to use a try catch if it will handle errors and prevent the program from crashing.
Taken from W3 Schools:
The try statement lets you test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.
The finally statement lets you execute
code, after try and catch, regardless of the result.
An example:
fuction foo()
{
try
{
// Block of code to try
}
catch(e)
{
// Block of code to handle errors
document.getElementById("demo").innerHTML = e.message;
}
finally
{
// Block of code to be executed regardless of the try / catch result
}
}
Here is soem more documentation at W3 Schools: http://www.w3schools.com/js/js_errors.asp
Yes, it absolutely good practice to use try-catch blocks. Here's a rather simplistic (but contrived) demonstration.
function safeParseJSON(json) {
try {
return JSON.parse(json);
} catch(exception) {
// could not parse this JSON
console.error(exception);
} finally {
return null;
}
}
Parsing JSON is the most common scenario I have encountered for using the try-catch construct, hence the example.
However, the usual try-catch mechanism doesn't work when the function is asynchronous. It's essential to understand this if you are ever using a server side Javascript platform.
The standard pattern for async event handling is as follows.
db.connect(options, function connected(err, client) {
if(err) throw err;
client.query(...);
});
Because that callback function is run somewhere else (presumably when the database connects) we can't wrap it with a try-catch block. Instead, most async method calls will pass the error as the first argument to the callback.
This way we can handle the error as and when it happens. If there is no error, null will be passed as the first argument, so that it can be ignored.
A number of implementations of promises try to recreate this mechanism, but in an asynchronous way.
Here's an example with Q:
db.connect(options)
.then(function(client) {
client.query(...);
})
.catch(function (error) {
throw error;
})
.fin(function() {
// finally
db.close();
});
You can also use Q on the client side, if you are working with asynchronous functions.

Disable error handling for mocha.js

Does anyone know if there a way to disable error handling by Mocha?
I'd really like to let the exception bubble up and be handled by the browser during debugging.
Update:
The context is this.
- Some code throw's an unexpected error.
- I would like to disable "try/catch" (something like jasmine's tests do) and be thrown into the debugger in chrome.
This way I can inspect the current state of the application at that moment.
It sounds like there isn't something built in, and I will need to manually do this each time I get some odd error in a test. Maybe by wrapping my code with
try {
somethingThatBreaks();
} catch(e) {
debugger;
}
Mocha installs its own onerror handler to trap exceptions that may occur in asynchronous code. You can disable it with:
window.onerror = undefined;
This is dangerous. You should do this only when you must absolutely do so. If you make this a routine thing, Mocha will completely miss errors that happen in asynchronous code.
If what you want to do is let exceptions in synchronous code bubble up, I'm not seeing what this would accomplish. If you want to inspect the exception before Mocha touches it, a try...catch block wrapping your test will do this.
Mocha's error handling is contained in the following code:
if (this.async) {
try {
this.fn.call(ctx, function(err){
if (err instanceof Error || toString.call(err) === "[object Error]") return done(err);
if (null != err) return done(new Error('done() invoked with non-Error: ' + err));
done();
});
} catch (err) {
done(err);
}
return;
}
// sync
try {
if (!this.pending) this.fn.call(ctx);
this.duration = new Date - start;
fn();
} catch (err) {
fn(err);
}
You could possibly throw the error with the catch (or remove the try..catch entirely) however it would most likely break the test suite if a test fails.
mocha.options.allowUncaught=true
But in this case, the rest of the tests will break if the error is not caught within mocha. Disabling try{} catch(){} in mocha will only be useful when debugging.
To create a test, I suggest using the construction
(for browser)
try{
throw new Error()
} catch (e){
// Let's say it's called in a yor error listeners.
e.handler=()=>{
done(e)
}
let event= new ErrorEvent('error',{error:e})
window.dispatchEvent(event);
}

Categories