Day 5 All about errors in nodejs

30 Days of Node

在这里插入图片描述

Inside this article !

  1. Introduction
  2. Errors in Node
  3. Properties of errors
  4. Propagation and interception
  5. Callbacks
  6. Why not Try-Catch
  7. About Errors
  8. Summary
  9. Repository

What are errors ?

Errors are any issue that arises unexpectedly and cause our program to not function properly , or halt its execution.

Errors in node.js

An errorobject in node.js does not specify any circumstances under which the error occured but errorobject does capture a stack trace which details the point in the code where the error was instantiated and may provide error description. All errors generated by node.js are either instantiated from errorclass or are intance of errorclass.

Node.js中的错误对象并未指定发生错误的任何情况,但是错误对象确实捕获了堆栈跟踪,该跟踪详细描述了代码中实例化错误的点,并可能提供错误描述。Node.js生成的所有错误都是从错误类实例化的,或者是错误类的实例

Properties of errors in node.js

  1. new Error(message) : It is used to create a new error object. It also sets error.messageproperty to the text specified.

    它用于创建新的错误对象。还将error.message属性设置为指定的文本

    const err = new Error('This is an error message');
    
  2. error.message : It shows the description of the error. It is set using new Error(msg)property. Mostly , the message “msg” comes in the first line of the error’s stack trace . An example is shown below

    // here error.message property is set to the string provided.
    const err = new Error('This is an error message');
    console.error(err.message);
    
    // Output will be
    // This is an error message
    
  3. error.code: This is a string label which is used to identify the type of error. It specifies errors in the form of node.js error codes.

    这是一个字符串标签,用于标识错误的类型。它以node.js错误代码的形式指定错误。

  4. error.stack: It returns a string in which details are provided about where in the code the error was instantiated.

    它返回一个字符串,其中提供了有关在代码中实例化错误的位置的详细信息

  5. Error.captureStackTrace : This is used to create a .stackproperty on the target object which returns the location in the code where Error.captureStackTrace()was called. It returns the data in the form of string.

    这用于在目标对象上创建一个.stack属性,该属性返回代码中调用Error.captureStackTrace()的位置。它以字符串形式返回数据。

  6. Error.stackTraceLimit : This property specifies number of stack frames captured by stack trace. It can be any valid JS number however 10 is the default value. If set to a non-number or negative number , then stack trace will not return any frames.

    此属性指定堆栈跟踪捕获的堆栈帧数。它可以是任何有效的JS数字,但是默认值为10。如果设置为非数字或负数,则堆栈跟踪将不返回任何帧。

Error propagation and interception in node.js

Node.js中的错误传播和拦截

In node.js , we are having several mechanisms for error propagating and handle those propagated errors while the application is in its running state. However the way in which these errors are reported and handled completely depends upon the type of error and API style.

在node.js中,我们具有几种机制来进行错误传播,并在应用程序处于运行状态时处理这些传播的错误。但是,报告和处理这些错误的方式完全取决于错误的类型和API样式。

  1. Synchronous APIs : These are those APIs which uses blocking method that does not accept a callback function and uses throwto report errors.

    同步API:这些API使用的阻塞方法不接受回调函数,并使用throw报告错误。

  2. Asynchronous APIs :

    Errors which occurs in asynchronous APIs can be reported in multiple ways as shown below :

    异步API中发生的错误可以通过多种方式报告,如下所示:

    • Errors can be routed to the object’s errorevent if an asynchronous event is called on an object.

      如果在对象上调用异步事件,则可以将错误路由到对象的错误事件。

      connection.on('error', (err) => {
          // This is the error event which is used to handle the error properly
      	// 这是错误事件,用于正确处理错误
          console.error(err);
      });
      
    • Very few asynchronous methods still use throwto raise exception which can further be handled using try/catchblock. (Not recommended)

      很少有在异步方法中仍然使用throw引发的异常,可以使用try / catch块进一步处理该异常。(不建议)

    • Asynchronous methods in node.js accepts an error object passed as the first argument given that method should accept callbacks. These errors are handled in the following way

      给定方法应该接受回调,node.js中的异步方法接受作为第一个参数传递的错误对象。这些错误的处理方式如下

      // Reading a File Asynchronously using nodejs
      // if any error occurs such as file not found
      // we don't have permissions , etc
      // then an err message will be console.
      
      const fs = require('fs');
      
      fs.readFile('message.txt', (err, data) => {
          if (err) 
              return console.error(err);
          console.log('Content: ' + data);
      });
      

Node.js styled callbacks

Node.js methods follows a idiomatic pattern which is knows as Node.js style callback . Following this pattern , we pass the callback function as an argument to the method. When the execution of the operation is completed or an error is raised then the callback function is called with error object if there exists any error object otherwise the first argument is passed as null.

Node.js方法遵循惯用模式,即Node.js Style callback。按照这种模式,我们将回调函数作为参数传递给方法。当操作执行完成或引发错误时,如果存在任何错误对象,则使用错误对象调用回调函数,否则将第一个参数作为null传递。

const fs = require('fs');

function nSCallback(error, data) {
    if (error) {
        console.error('Error: ', error);
        return ;
    }
    console.log(data);
}

fs.readFile('file_that_exists', nSCallback);
fs.readFile('file_does_not_exists', nSCallback);

Why not try/catch

We cannot use try/catchmechanism to intercept the errors generated by asynchronous APIs.
Note : The snippet Given below is invalid

我们不能使用try/catch机制来拦截异步API生成的错误。

注意:下面给出的代码段无效

// Invalid Snippet
// An asynchronous operation which will generate error
try {
    async_method('invalid_arguments_generate_error', (err, data) => {
        if (err) {
            throw err;
        }
    });
} catch (err) {
	console.error(err);
}

This is a very common mistake with beginners. This will not work because the method is asynchronous. The time by which the callback will be called , surrounding code already completed its execution and exited. Throwing an error inside the callback can leads to the crashing of node.js process in most of the cases.

这是初学者很常见的错误。因为该方法是异步的,所以这将不起作用。回调被调用的时间将发生在周围的代码已经执行完成并退出后。在大多数情况下,在回调中引发的错误可能会导致node.js进程崩溃。

About errors

In node.js applications , mostly all the errors belong to one of the mentioned categories

Standard javascript errors :

  • < URI > error : This error is thrown when a global URI handling function is misued.

    滥用全局URI处理功能时,将引发此错误

  • < Eval > error : This error is thrown when the call to eval()fails.

    调用eval()失败时,将引发此错误

  • < Type > error : This is a subclass of error which shows that the argument provided is not of allowed type.
    for e.g. passing an objectwhere a stringis expected would be considered a TypeError.

    这是错误的子类,它表明提供的参数不是允许的类型

    例如传递期望字符串的对象将被视为TypeError

  • < Range > error : This is a subclass of error which shows that the argument provided was not within the range of acceptable values.
    这是错误的子类,它表明提供的参数不在可接受的值范围内

  • < Syntax > error : This is a subclass of error which indicates that the code written is not of valid Javascript.
    这是错误的子类,指示所写的代码不是有效的Javascript

  • < Reference > error : This is a subclass of error which signifies that an attempt is made to access a variable which is not defined. These are very common typos or broken code .
    这是错误的子类,表示尝试访问未定义的变量。这些是非常常见的错别字或破损的代码

  1. System errors :

    This type of errors are generated when the exception occurs during the run time of the program. They are generated when the application violated some constraints of operating system.

    当程序运行期间发生异常时,会生成此类错误。当应用程序违反操作系统的某些约束时,将生成它们

    Properties of system errors :

    系统错误的属性:

    • error.code : This is a string which represents and error code. some common examples include EACCES , EADDRINUSE , ECONNREFUSED , etc .

      这是代表错误代码的字符串。一些常见的例子包括EACCES,EADDRINUSE,ECONNREFUSED等

    • error.port : This is a number which represents the connection’s port which is unavailable.

      这是代表连接端口是不可用的数字

    • error.address : This is a string which represents the address to which the connection failed.

      它是一个字符串,代表连接失败的地址。

    • error.path : This is a string which represents the relevant invalid pathname .

      这是代表相关无效路径名的字符串

    • error.syscall : This is a string which represents the failed syscall.

      这是代表失败的系统调用的字符串

    • error.errno : This property can be a number or a string. If number , the value will be negative which corresponds to the error code. If string , it is same as error.code.

      此属性可以是数字或字符串。如果为number,则该值将为负,与错误代码相对应。如果是字符串,则与error.code相同。

  2. User-specified errors : This type of errors are generated by application code.

    用户指定的错误:这类错误是由应用程序代码生成的

  3. Assertion errors : This type of errors are raised by assert. This type of errors are special case of errorswhich occurs when an exceptional logic violation is detected in node.js that should never occur.

    断言错误:此类错误由assert引发。这种类型的错误是错误的特殊情况,当在node.js中检测到异常逻辑违规(永远不应该发生)时,就会发生这种错误。

Summary

In this part of the node.js series,we learned about errors. We learned what are errors and errors in node.js and properties of errors in node.js.
We also learned about error propagation and interception in nodejs , what is the concept of node.js styles callbacks and why it is better to avoid try/catch while using asynchronous functions. Lastly we learned about the 4 categories most of the errors belong to which are Standard javascript errors , system errors , user-specified errors and assertion errors .

hy it is better to avoid try/catch while using asynchronous functions. Lastly we learned about the 4 categories most of the errors belong to which are Standard javascript errors , system errors , user-specified errors and assertion errors .

了解了什么是node.js中的错误以及node.js中的错误属性。还了解了nodejs中的错误传播和拦截,node.js style callback的概念以及为什么在使用异步函数时最好避免try / catch的原因。最后,我们了解了4个类别,其中大多数错误属于标准javascript错误,系统错误,用户指定的错误和声明错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值