first time getting this error Uncaught Error in Console - javascript

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.

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

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.

"rejected promise not handled within 1 second" vscode Extension API

I'm trying to write a simple extension for VS code that renames a selection to a given string. The app was bootstrapped with the extension generator: https://code.visualstudio.com/docs/extensions/example-hello-world#_generate-a-new-extension
For this I use this code:
const editor = vscode.window.activeTextEditor;
if (!editor) throw Error;
const position = editor.selection.active
const uri = editor.document.uri
vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", uri, position, "donkey")
.then(edit => {
if (!edit) throw Error;
return vscode.workspace.applyEdit(edit);
});
The command is bound to a keybinding. I launch the debugger with F5(launching an instance of vs code for debugging like in the tutorial: https://code.visualstudio.com/docs/extensions/example-hello-world#_debugging-your-extension ). I then select a bunch of code in a file that I opened in that debugging instance and press my keybinding.
However, in the Debug Console I get "rejected promise not handled within 1 second". No error is thrown and since executeCommand is a Thenable, not a real Promise, I can't call catch() on it.
I tried to wrap the call in a try/catch block but with no success.
When i try other to do other stuff, like showing a message with vscode.window.showInformationMessage or prompt the user for input it works and I don't see the error.
I also tried to do the same with a Typescript version of the extension, but I get the same behavior.
I don't see what I am doing wrong, is there something I am missing ?
Thenable.then takes two arguments: a success continuation and a failure continuation. You can use the failure continuation to make sure rejections are properly handled:
vscode.commands.executeCommand("vscode.executeDocumentRenameProvider", uri, position, "donkey")
.then(edit => {
if (!edit) throw Error;
return vscode.workspace.applyEdit(edit);
})
.then(undefined, err => {
console.error('I am error');
})
This way, if executeCommand, the previous then, or applyEdit fail, the rejection is properly handled

Promise resolve just for success?

I'm writing an simple REST API in JavaScript and i wonder whats the best approach when using Promises and resolving/rejecting mechanism.
At first i wanted to make promise signature like:
MyApi.getSomeData()
.then(responseSuccess => console.log(responseSuccess))
.catch(responseError => console.log(responseError)
where success means we got i.e. code 200 and have some data but error means i.e. we get 404 from server. I wanted to ensure that end user that will use the API methods will have guarantee the on error(catch) he'll get particular object.
But what if the promise throws some exception somewhere inside (some runtime error or some such)? Then the promise will be rejected with this Error instead of my responseError structure.
Whats the best approach in those cases? How to distinguish between operation success, operation failure (but intentionally, i.e. 404 code) and operation unexpected error?
Run time errors in the promise will trigger the catch block. There is no avoiding that. You can however distinguish between runtime errors and network errors by checking the body of the error. So suppose
responseError = {
type: 'NETWORK_ERROR',
status: 400,
message: 'Invalid input'
}
if (responseError.type === 'NETWORK_ERROR') {
// Network error code here
} else {
// All other types of errors
}
You can also abstract this logic in a common place so you can reuse it.

How to catch promise runtime Javascript errors?

I'm currently implementing a PDF viewer based on PDF.js and as part of that I learned about promise objects.
I also learned that runtime errors are not automatically shown in the debugging console:
PDFJS.getDocument(...).then(
function(pdfDocument){
alert(UndefinedVariable); // Not shown in console!
},
function(error){
console.log("Error occurred", error);
}
);
I haven't been able to find a pretty way to show runtime errors in the promise functions, other than adding .done() as described in http://www.asyncdev.net/2013/07/promises-errors-and-express-js/ (which doesn't work for PDF.js) or adding .catch(function(error){ console.error(error); }).
I know that I can break on exceptions from runtime errors in the debugger, but I also get breaks on other exceptions (in jQuery) by doing so, which means I have to step thorugh 5 jQuery exceptions on every page load, before I can even check if my own code contains runtime errors.
Is there any way to force the promise functions to log runtime errors like normal (without writing extra code for every function call)?
The problem you're experiencing is that an exception in the then callback does reject the promise returned by .then(), instead of calling the error handler that you passed in. That will only trigger for errors in the promise on which you called .then(). So you can chain your handlers:
PDFJS.getDocument(...).then(function(pdfDocument){
alert(UndefinedVariable); // Now shown in console!
}).then(null, function(error){
console.log("Error occurred", error);
});
Here, then(null, …) could also be abbreviated by catch(…).
If there is no done method that throws on errors, you could implement it yourself like this by throwing in a setTimeout.
Is there any way to force the promise functions to log runtime errors like normal (without writing extra code for every function call)?
No. That's just not how they were designed.
In the Promise implementation, there is a try ... catch which takes an error from the callbacks and turns it into an error returned by the Promise.
One thing you can do is change that try...catch to log the errors before invoking the failure of the promise.
https://github.com/mozilla/pdf.js/blob/master/src/shared/util.js#L936
} catch (ex) {
console.error(ex); // <--- add this line
nextStatus = STATUS_REJECTED;
nextValue = ex;
}
If native ECMAScript 6 promises are used instead, this trick probably won't work.

Categories