At object anonymous как исправить
Перейти к содержимому

At object anonymous как исправить

  • автор:

15 Common Error Codes in Node.js and How to Fix Them

Author's avatar

You will encounter various kinds of errors while developing Node.js applications, but most can be avoided or easily mitigated with the right coding practices. However, most of the information to fix these problems are currently scattered across various GitHub issues and forum posts which could lead to spending more time than necessary when seeking solutions.

Therefore, we've compiled this list of 15 common Node.js errors along with one or more strategies to follow to fix each one. While this is not a comprehensive list of all the errors you can encounter when developing Node.js applications, it should help you understand why some of these common errors occur and feasible solutions to avoid future recurrence.

�� Want to centralize and monitor your Node.js error logs?

Head over to Logtail and start ingesting your logs in 5 minutes.

1. ECONNRESET

ECONNRESET is a common exception that occurs when the TCP connection to another server is closed abruptly, usually before a response is received. It can be emitted when you attempt a request through a TCP connection that has already been closed or when the connection is closed before a response is received (perhaps in case of a timeout). This exception will usually look like the following depending on your version of Node.js:

If this exception occurs when making a request to another server, you should catch it and decide how to handle it. For example, you can retry the request immediately, or queue it for later. You can also investigate your timeout settings if you'd like to wait longer for the request to be completed.

On the other hand, if it is caused by a client deliberately closing an unfulfilled request to your server, then you don't need to do anything except end the connection ( res.end() ), and stop any operations performed in generating a response. You can detect if a client socket was destroyed through the following:

2. ENOTFOUND

The ENOTFOUND exception occurs in Node.js when a connection cannot be established to some host due to a DNS error. This usually occurs due to an incorrect host value, or when localhost is not mapped correctly to 127.0.0.1 . It can also occur when a domain goes down or no longer exists. Here's an example of how the error often appears in the Node.js console:

If you get this error in your Node.js application or while running a script, you can try the following strategies to fix it:

Check the domain name

First, ensure that you didn't make a typo while entering the domain name. You can also use a tool like DNS Checker to confirm that the domain is resolving successfully in your location or region.

Check the host value

If you're using http.request() or https.request() methods from the standard library, ensure that the host value in the options object contains only the domain name or IP address of the server. It shouldn't contain the protocol, port, or request path (use the protocol , port , and path properties for those values respectively).

Check your localhost mapping

If you're trying to connect to localhost , and the ENOTFOUND error is thrown, it may mean that the localhost is missing in your hosts file. On Linux and macOS, ensure that your /etc/hosts file contains the following entry:

You may need to flush your DNS cache afterward:

On Linux, clearing the DNS cache depends on the distribution and caching service in use. Therefore, do investigate the appropriate command to run on your system.

3. ETIMEDOUT

The ETIMEDOUT error is thrown by the Node.js runtime when a connection or HTTP request is not closed properly after some time. You might encounter this error from time to time if you configured a timeout on your outgoing HTTP requests. The general solution to this issue is to catch the error and repeat the request, preferably using an exponential backoff strategy so that a waiting period is added between subsequent retries until the request eventually succeeds, or the maximum amount of retries is reached. If you encounter this error frequently, try to investigate your request timeout settings and choose a more appropriate value for the endpoint if possible.

4. ECONNREFUSED

The ECONNREFUSED error is produced when a request is made to an endpoint but a connection could not be established because the specified address wasn't reachable. This is usually caused by an inactive target service. For example, the error below resulted from attempting to connect to http://localhost:8000 when no program is listening at that endpoint.

The fix for this problem is to ensure that the target service is active and accepting connections at the specified endpoint.

5. ERRADDRINUSE

This error is commonly encountered when starting or restarting a web server. It indicates that the server is attempting to listen for connections at a port that is already occupied by some other application.

The easiest fix for this error would be to configure your application to listen on a different port (preferably by updating an environmental variable). However, if you need that specific port that is in use, you can find out the process ID of the application using it through the command below:

Как устранить эту ошибку "at Object. <Anonymous>" в jest.js

У меня много глобальных объектов и я говорю о функции, которую нужно протестировать, но когда я запускаю npm test, я получаю объект. (index.js: 2: 1) в объекте. (index.test.js: 1:1) эта ошибка указывает на объект «.» из gblob.aobj = <>; для простоты я создал файл index.js и index.test.js, я новичок в jest.js

примечание: я работаю над SPA: одностраничное приложение, где эта переменная создается в другом JS

How to resolve this "at Object.<anonymous> " error in jest.js

I have lots of global objects and say a function which is to be tested but when I run npm test i get at Object. (index.js:2:1) at Object. (index.test.js:1:1) this error this error points at the object «.» of gblob.aobj=<>; for simplicity sake i have created a index.js and index.test.js file ,im new to jest.js

note: im working on SPA: single page application where this variable is created in another js

Custom JavaScript Errors in ES6

Jamund Ferguson

A few years ago I gave a talk at MountainWest JS called Error Handling in node.js. In that talk I extolled the virtues of creating custom error objects by extending the built-in Error type. Most of the content was inspired by Guillermo’s seminal A String is Not an Error. Let’s revisit that advice in the world of ES6 classes.

Why Do We Care About Error Objects?

Error objects are the only way to get stack traces in JavaScript. If you callback with or throw or reject a promise with a string instead of an Error, you won’t be able to trace where the error came from.

Here’s a simple example:

When you run this file in Node 6 you’ll see:

Here’s what creating a real Error object looks like

The output which is much better:

Tip: There’s an ESLint rule no-throw-literal that will catch many of these errors.

Why Bother with Custom Errors?

Given that Error objects are much better than strings, what if we need to include more than a message with our error? For example what if we also want to include an error code?

One of the common ways to handle this is to append errors with custom properties (which is used heavily in node.js itself.)

This is a very reliable approach, but has two downsides:

  1. It can be a lot of lines of code (1 line per extra property)
  2. Your error instance can’t have any custom methods

Why would you want these extra features?

Think about the case of dealing with errors from a server request. Maybe multiple form fields had errors in them or maybe you need a CAPTCHA included to continue. Encapsulating all of that logic in a custom error class might make a lot of sense:

The idea here is that we can create a special ServerError class which can take all of the data from the bad server response and append the error object with critical information including statusCode, as well as any error code, or maybe even an array of with all of the forms fields which are failing. We could even give our ServerErrror special methods like getLocalizedError() which wouldn’t be available with a standard error object.

How Do We Make Custom Errors?

Making custom error objects used to be a little bit tricky! Lots of blog posts had to be written about it (mostly because inheritance in JS is a little bit tricky.) Thankfully ES6 has made this a little bit easier.

Here’s an example of creating a custom error with ES6:

That was pretty simple! Let’s see what sort of stack trace this error creates:

Here’s what gets logged:

This looks like a normal stack trace except for one thing. It includes the error constructor in the stack trace. This is not actually a big deal, but if you want to kick that you can do this:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *