Cannot catch exception thrown by mixpanel.track - javascript

I'm using mixpanel for tracking / analytics in my Ionic+Angular project. I want to catch the exception thrown by the mixpanel.track.
Tried Methods?
mixpanel.track returns Promise, on which I did tried using catch handler, but the issue I came to know is mixpanel.track is always(mostly?) resolving this Promise with the OK string immediately, and then after that when it actually sends the event back to sentry server, it throws the error around - Missing value for and so on (the error here is not the concern, but the handling of it is).
mixpanel.track('MyEventName', myEventProperties).then(data => {
console.log('Even when there is error, mixpanel return OK in data, ', data);
}).catch(err => {
console.log('Not getting the mixpanel error in here as expected', err);
})
Is there any way / mixpanel API which I'm supposed to use in order to get these exceptions that I can handle more gracefully, or is this some sort of bug with the mixpanel that should be fixed by them?

Related

NestJS blocking new requests after throwing error

I've got a small testing application (a test lab) with an AppControler and an AppService, AppController has a GET endpoint and send requests payload to AppService, which has two async methods.
AppService
async requestTesting (payload): Promise<void> { // This is what's being called from the controller
if(payload) {
await this.validateErrorHandling(payload)
}
console.log('TESTING', payload)
// DO STUFF
}
async validateErrorHandling(payload): Promise<void> {
console.log('DO STUFF')
if(payload && payload.number > 2) { // This is true
throw new Error()
}
}
When requestTesting calls validateErrorHandling, the second method is going to check that condition (if truthy) and shall throw an Error.
I'm used to do this with an exception filter on real use cases, but in this very specific case, whenever I call my Controller's endpoint and that error is thrown on my AppService, the following is shown:
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 "........".
And I'm unable to make any other request through postman until I restart the app.
Postman shows:
Error: connect ECONNREFUSED 127.0.0.1:3000
Now, I'm aware that a try/catch should fix this, but I'm trying to understand why this is stopping my whole application instead of stopping the function execution only, as it never happened to me before, and if I try to throw it anywhere else, it just works.
Now, both methods have a Promise<void> return type, but if validateErrorHandling throws an error, everything should stop and that console.log('TESTING', payload) should not be executed (as if it were business logic).
I'm afraid it's not just me being silly, but I might actually be missing something.
The reason that we throw an error is that we want to tell the front application that something went wrong. In order to achieve this, it's better to throw an HTTP error instead of simply throwing it. So here is the code:
throw new UnprocessableEntityException({
errorCode: UpdateProductErrorStatusEnum.DeviceNotReported,
message: UpdateProductErrorMsgEnum.DeviceNotReported,
});
You have two options. First throw the error in the service itself, second to throw an Error (as you did) and catch it in the controller layer. Each way has its own pros and cons. Throwing in the controller is better because the controller is designed to handle HTTP related stuff, and service is created for only logic stuff. But throwing in the controller makes the controller messy and maybe your code will not be clean.
See here for more info: https://docs.nestjs.com/exception-filters

first time getting this error Uncaught Error in Console

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.

When and why use subscribe's error handler?

I've noticed that even if I don't include the error handler in my subscribe call back, my error will still get logged to the console. It seems like Angular logs all errors to the console by default, am I right in this assumption?
For example if I include the error handler:
console.log("beep");
of(1,2,3,4).pipe(
mergeMap(data => {
if (data === 3) {
return throwError('Error Occurred for data: '+ 3);
}
return of(data);
})
).subscribe(res => console.log(res),
err => console.error(err)
);
console.log("bop");
The output in my browser console is
beep
1
2
Error Occurred for data: 3
bop
Now if I take out the error handler in my subscribe, like so
console.log("beep");
of(1,2,3,4).pipe(
mergeMap(data => {
if (data === 3) {
return throwError('Error Occurred for data: '+ 3);
}
return of(data);
})
).subscribe(res => console.log(res)
);
console.log("bop");
I get this in my console:
Beep
1
2
Bop
ERROR Error Occurred for data: 3
What's causing this discrepancy? I know throwError returns an Observable that emits an error notification, and errorHandler (ends the stream lifecycle?) and receives the error. So if I take out the errorHandler, is the throwError Observable being treated like a value by the success handler function?
And in general I feel like it's unnecessary to do any type of error handling for things like http and stuff, cause even if I leave the error handler off my subscribe callback, angular seems to take care of errors for me by logging 404 not found messages and such to the console.
If all you want to do when you hit an HTTP error is log an error message to the console then you don’t need to subscribe to the error handler. You should not subscribe to error handlers (or catch exceptions) unless you can handle them in some way.
Sometimes however you might want to do something different. Maybe there is a backup server you can try. Maybe you want to redirect the user to a different error page. Maybe you can just disable one part of the site and everything else can keep working. Maybe the error means the server is busy and you should retry in 30 seconds.
In these cases you would want to subscribe to that error handler and take action. Although, even then, you might use a catch operator or some other mechanism.

Unhandled Rejection(Error) when trying to disconnect from Twillio Room

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(() => {})

Promises - catch is not working

Why is it that the following code doesn't catch the exception being thrown?
$http.get(null) // <- this throws a fit
.catch(function (e) {
console.log(e); // <- this is not being triggered
});
Error: [$http:badreq] Http request configuration url must be a string or a $sce trusted object. Received: null
https://errors.angularjs.org/1.7.2/$http/badreq?p0=null
.catch() is not a replacement for normal try catch.
It is specifically for handling exceptional circumstances that occurred during the promise resolution process.
In this case, the exception (throwing a fit) is happening outside the promise resolution process.
Your supplying invalid input to the $http.get method causing an exception before an XHR even gets created, not something going wrong with the HTTP request or any subsequent processing.
Here is an equivalent of what is happening:
try {
$http.get(throwAnException())
// .catch isn't even being evaluated!
.catch(function(e) {
console.error(e); // no chance of being called
});
} catch (e) {
// I would be evaluated
console.error(e);
}
function throwAnException() {
throw "An error before we even start";
}
You need to understand that this catch is waiting for a "rejection" from your get call.
In other words, your $http.get is triggering an error and never returning a promise...this way, you can't execute a catch straight from an error, get it?
If you have $http.get("xyz") it will then do its thing and reject, therefore, being caught by your catch.
What you are doing results in this
// step 1
$http.get(null)
.catch()
// step 2
ERROR
.catch() // will not even get here, but if it did, it wouldn't work either
While, if your get could work, but rejected, you would have:
// step 1
$http.get('someFailingURL')
.catch()
// step 2
RejectedPromise
.catch() // gonna work :)
If your url comes from a different source (and that's why you get a null value for it some times) you should probably validate it before trying and getting it, like so:
if (yourVariableURL !== null) {
$http.get(yourVariableURL)
.catch()
} else {
console.log('Invalid url');
}
This will throw Error: $http:badreq Bad Request Configuration. It has issue at request parameter level where string/url is expected but not null. Hence not going inside the block. That is the reason it is not triggering catch.
The error will be thrown by Angular is as below -
Http request configuration url must be a string or a $sce trusted object. Received: null
This error occurs when the request configuration parameter passed to the $http service is not a valid object. $http expects a single parameter, the request configuration object, but received a parameter that was not an object or did not contain valid properties.
To resolve this error, make sure you pass a valid request configuration object to $http.
Additionally, if required to catch the issue with this block of code itself, wrap it in try-catch block.

Categories