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
Related
I want to add information to an Error object in typescript/javascript. I currently do it like this:
try {
// code that might throw code
} catch (e) {
throw new Error(`Error while processing file ${path}:\n${e}`);
}
But that removes the information from the previous error.
Java/PHP both have a previous parameter in exceptions so I can wrap the error and preserve/extend the original information but I can't seem to find an equivalent in JavaScript.
How would I do that?
So there is no standard way.
However, if your intention is just to add information to the exception message, without messing with the error itself, you can just extend the message property
try {
} catch (e) {
e.message = `File: ${path}\n${e.message}`;
throw e;
}
This will preserve the proper stack trace and will display like you expect in chrome or on the node console.
Here an example exception:
Error: File: 6ff6255b-45b5-4895-8d59-50fa60663cfc.json
JSON Schema: schemas/schema.json
- must NOT have additional properties
at JsonFs.validate (driver/json-fs.ts:60:19)
at JsonFs.readSource (driver/json-fs.ts:39:14)
at async JsonFs.readSourceFile (driver/abstract-fs.ts:82:30)
at async driver/abstract-fs.ts:46:34
When I use try, catch I can get line number of error by stack message.
But When I use this for ajax call as below,
try {
await axios.get('http://example.com')
} catch (error) {
console.log(error)
}
I can't get the stack error. It just gives me error of ajax call.
Isn't there any method for catching the line number in this case?
Thank you for reading it.
Usually, error will contain enough information to identify the problem. error is an object, when you do console.log(error), it actually calls its toString implementation.
To get the stack only, you can use.
try {
throw new Error('Test');
} catch (error) {
console.log(error.stack);
}
The above will only point to the JavaScript file/piece of code that fires the request to example.com, nothing more. :)
If you want to see what happened with your call (more details of why it failed), and what was the response, try console.log(JSON.stringify(error)) and use Network DevTools - https://developers.google.com/web/tools/chrome-devtools/network
i am working on a ToDo list and its basically done. but i am getting this error in the console that i haven't come across yet, its preventing me to create the list (to do list)
This is the error im getting:
OPTIONS http://localhost:4000/cpds/add
net::ERR_NAME_NOT_RESOLVED
Uncaught (in promise) Error: Network Error createError.js:17
at createError (createError.js.17)
at XMLHttpRequest.handelError (xhr.js:80)
Can someone please explain what this means and how to resolve this issue.
the list prints in my console but not in my browser, then prints this error afterwards.
ERR_NAME_NOT_RESOLVED - points that system fail to resolve IP address for given hostname (http://localhost:4000/cpds/add in your case). While it is very unlikely that you are realy could not resolve address for localhost itself most probable reason is that you requesting for closed port (:4000).
In general this message say Uncaught which means that somewhere in you code when you request for "http://localhost:4000/cpds/add" form axios (it is assumtion cause you don't gave any details about your code) you have statement like
axios.get(url, { headers })
.then(data => console.log(data))
without
.catch(error => console.error(error))
so full version is
axios.get(url, { headers })
.then(data => console.log(data))
.catch(error => console.error(error))
So when request is fails due to any reason (probably error in url in you case) interpreter don't know how to overcome it (other words you should directly define function which would be called in case of error and pass it to catch method).
To ensure error is in url try to place http://localhost:4000/cpds/add to address bar of you browser, if it is realy unaccessable, browser should show you an error.
This is because one of your calls returned a rejected promise/async function, or in other words: An error that occurred calling your function.
Be careful about this. You can write yourlibrarycall.then(result => ...).catch(error => ...) But this can quickly get a pitfall. The catch clause will be called if the library call failed, but also when the .then clause failed. You'd expect the failure came from the library call, but this was fine, your code might also had a problem and the value that the variable error returns might be totally different (or undefined).
Hence i prefer having:
yourFunction = async () => {
let result;
try {
result = await yourlibrarycall // this is blocking
}
catch (error) {
// error handling only of your library call
}
// here comes your following logic
...
}
Using asnyc, your function is executed asynchronously and can now wait for the result using the keyword await. If the library call failed, it will enter the catch scope and provide you a variable with the error occurred.
This is now all the error handling and only will now only cope with the request, the following logic is then executed afterwards, getting rid of the misleading .then(...).catch(...).
If you still want to use the promise approach instead of async/await be careful to handle all the errors in the catch clause explicitly, otherwise they'll bubble up and will be catched by the catch clause, as stated above.
In my twillio application i'm getting random errors when tryin to disconnect from the room.
This is the code I'm trying to execute upon exit:
this.log('Leaving room...');
try {
this.activeRoom ? this.activeRoom.disconnect().catch(console.log) : console.log('No active room to disconnect / check disconnect logic');
} catch (error) {
console.log(error)
}
this creates the following error:
I'm not so concerned about the error itself but the fact that i cannot catch the error.
As you can see both try/catch block and .catch() were added but I'm still getting this error.
UPDATE_1
After digging thru the api I found and implemented this:
this.activeRoom.on('disconnected', function(room, error) {
if (error) {
console.log('Unexpectedly disconnected:', error);
}
myRoom.localParticipant.tracks.forEach(function(track) {
track.stop();
track.detach();
});
});
however this error still comes up for me.
UPDATE_2
After implementing solution proposed in an answer this is what I got(still the same error):
For anyone that runs into this issue. The stack trace you get from room.disconnect() is misleading.
The actual error is in your room.localParticipant.publishTrack(track) call. That function returns a promise, and will resolve (with an exception) the moment you call room.disconnect().
If you haven't handled failure there, you'll get the error shown in this question. So just add a .catch() statement to all your publishTrack calls.
Twilio developer evangelist here.
That is weird that you can't seem to catch the error. I'm not sure I have an answer for that.
However, you could check whether the local participant is connected before trying to disconnect them. A Participant object has a state property that can be "connected", "disconnected" or "failed".
So, you could:
if (this.activeRoom && this.activeRoom.localParticipant.state === 'connected') {
this.activeRoom.disconnect();
}
I use this to solve this issue
(new Promise(() => room.disconnect())).then(() => {}).catch(() => {})
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)
}
}