Node.js Errors模块
Errors
- Error Propagation and Interception
- Node.js style callbacks
- Class: Error
- new Error(message)
- Error.captureStackTrace(targetObject[, constructorOpt])
- Error.stackTraceLimit
- error.message
- error.stack
- Class: RangeError
- Class: ReferenceError
- Class: SyntaxError
- Class: TypeError
- Exceptions vs. Errors
- System Errors
- Class: System Error
- error.code
- error.errno
- error.syscall
- Common System Errors
- Class: System Error
Errors
错误;过失;失误;
Applications running in Node.js will generally experience four categories of errors:
- Standard JavaScript errors such as:
- <EvalError> : thrown when a call to eval() fails.
- <SyntaxError> : thrown in response to improper JavaScript language syntax.
- <RangeError> : thrown when a value is not within an expected range
- <ReferenceError> : thrown when using undefined variables
- <TypeError> : thrown when passing arguments of the wrong type
- <URIError> : thrown when a global URI handling function is misused.
- System errors triggered by underlying operating system constraints such as attempting to open a file that does not exist, attempting to send data over a closed socket, etc;
- And User-specified errors triggered by application code.
- Assertion Errors are a special class of error that can be triggered whenever Node.js detects an exceptional logic violation that should never occur. These are raised typically by the assert module.
All JavaScript and System errors raised by Node.js inherit from, or are instances of, the standard JavaScript class and are guaranteed to provide at least the properties available on that class.
运行在Node.js上的程序,通常会经历这4个类型的错误。
标准的JavaScript错误如下:
- <EvalError>: 当eval() 函数执行失败时被抛出。eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码(如果有的话)。
- <SyntaxError>: 响应不合适的JavaScript语法时被抛出。
- <RangeError>: 当一个值不在预期的范围内时被抛出。
- <ReferenceError>: 当使用未定义的变量时被抛出。
- <TypeError>: 当转换错误类型的参数时被抛出。
- <URIError>: 当一个全局的URI处理函数被误用时抛出。
系统错误是由底层操作系统约束引起的,比如尝试去打开一个不存在的文件,尝试在一个已经关闭的套接字上发送数据,等等。
- 用户自定义错误是由应用程序错误码引起的。
- 断言错误是一个特殊的错误类,每当Node.js检测到一个例外的逻辑违反时就会触发,但它不应该被触发。这类错误通常由断言模块引起。
Node.js中所有被抛出的JavaScript和系统的错误都继承自或者由JavaScript的<Error>类实例化,并且保证提供至少一个可以获取的属性。
Error Propagation and Interception
错误继承和拦截
Node.js supports several mechanisms for propagating and handling errors that occur while an application is running. How these errors are reported and handled depends entirely on the type of Error and the style of the API that is called.
All JavaScript errors are handled as exceptions that immediately generate and throw an error using the standard JavaScript throw mechanism. These are handled using the try / catch construct provided by the JavaScript language.
Node.js支持多种继承机制和在程序运行时的错误处理。异常如何报告并且如果处理完全依赖于错误的类型和被调用的API的风格。
所有的JavaScript的错误都被当做即时生成的异常处理并且使用标准的JavaScript机制抛出异常。它们可以使用JavaScript语言提供的try/catch构造函数来处理。
// Throws with a ReferenceError because z is undefined
// 抛出一个引用异常,因为z未定义
try {
const m = 1;
const n = m + z;
} catch (err) {
// Handle the error here.
//在这里处理异常
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
Any use of the JavaScript throw mechanism will raise an exception that must be handled using try / catch or the Node.js process will exit immediately.
With few exceptions, Synchronous APIs (any blocking method that does not accept a callback function, such as fs.readFileSync), will use throw to report errors.
Errors that occur within Asynchronous APIs may be reported in multiple ways:
任何使用JavaScript的抛出机制都会产生一个异常,必须使用try/catch来处理,否则Node.js进程就会立即退出。
少数的异常,同步APIs(任何不接受回调函数的阻塞方法,比如fs.readFileSync)都会使用抛出的方式来报告异常。
异步APIs里产生的错误可能会通过多种方式进行报告。
- Most asynchronous methods that accept a callback function will accept an Error object passed as the first argument to that function. If that first argument is not null and is an instance of Error, then an error occurred that should be handled.
大部分异步方法都接受一个回调函数,该函数接收一个错误对象作为它的第一个参数。如果第一个参数不是null,并且是错误对象的实例,就表示有一个需要被处理的错误产生了。
const fs = require('fs');
fs.readFile('a file that does not exist', (err, data) => {
if (err) {
console.error('There was an error reading the file!', err);
return;
}
// Otherwise handle the data
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- When an asynchronous method is called on an object that is an EventEmitter, errors can be routed to that object’s ‘error’ event.
当事件发生器对象上的一个异步方法被调用时,错误会被路由到那个对象的错误事件上。
const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
//为这个流添加错误事件处理
connection.on('error', (err) => {
// If the connection is reset by the server, or if it can't connect at all, or on any sort of error encountered by the connection, the error will be sent here.
//如果连接被服务器重置,或者根本不能连接,或者连接遭遇到了任何形式的错误,错误就会被送到这里。
console.error(err);
});
connection.pipe(process.stdout);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- A handful of typically asynchronous methods in the Node.js API may still use the throw mechanism to raise exceptions that must be handled using try / catch. There is no comprehensive list of such methods; please refer to the documentation of each method to determine the appropriate error handling mechanism required.
在Node.js API中少许典型的异步方法可能还在使用抛出机制来产生异常,它必须使用try / catch来处理。并没有这样的方法的综合列表;可以参考每个方法的文档来判断所需的合适的异常处理机制。
The use of the ‘error’ event mechanism is most common for stream-based and event emitter-based APIs, which themselves represent a series of asynchronous operations over time (as opposed to a single operation that may pass or fail).
For all EventEmitter objects, if an ‘error’ event handler is not provided, the error will be thrown, causing the Node.js process to report an unhandled exception and crash unless either: The domain module is used appropriately or a handler has been registered for the
process.on('uncaughtException')
event.
使用错误事件机制在基于流和基于事件触发的API中是最为常见的。它们自身逐渐代表了一系列的异步操作(而不是单一的操作,可能通过或失败)。
对于所有事件触发器对象,如果没有提供错误事件的处理器,错误就将会被抛出,导致Node.js线程报告一个未捕获的异常同时崩溃,除非:整个模块都被恰当的使用或者已经注册了process.on('uncaughtException')
的事件处理器。
var myEvent = new events.EventEmitter();
setImmediate(()=>{
// This will crash the process because no 'error' event handler has been added.
//线程将会崩溃,因为没有'error'事件捕获机制被添加。
myEvent.emit('error', new Error('This will crash'));
});
- 1
- 2
- 3
- 4
- 5
- 6
Errors generated in this way cannot be intercepted using try / catch as they are thrown after the calling code has already exited.
Developers must refer to the documentation for each method to determine exactly how errors raised by those methods are propagated.
以这种方式产生的错误不能被try/catch拦截,因为它们是在调用的大妈执行结束后才被抛出的。
开发者一定要参考每一个方法的文档来恰当地决定如何传递这些方法引起的错误。
Node.js style callbacks
Most asynchronous methods exposed by the Node.js core API follow an idiomatic pattern referred to as a “Node.js style callback”. With this pattern, a callback function is passed to the method as an argument. When the operation either completes or an error is raised, the callback function is called with the Error object (if any) passed as the first argument. If no error was raised, the first argument will be passed as null.
大部分由Node.js内核API暴露的异步方法都遵循一个符合Node.js回调风格的语言模式。使用该模式,回调函数可以作为一个参数被传递。当操作完成或者错误产生以后,该回调函数就会被调用,带一个错误对象(如果有的话)作为第一个参数。如果没错误产生,第一个参数就会传空。
const fs = require('fs');
function nodeStyleCallback(err, data) {
if (err) {
console.error('There was an error', err);
return;
}
console.log(data);
}
fs.readFile('/some/file/that/does-not-exist', nodeStyleCallback);
fs.readFile('/some/file/that/does-exist', nodeStyleCallback)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
The JavaScript try / catch mechanism cannot be used to intercept errors generated by asynchronous APIs. A common mistake for beginners is to try to use throw inside a Node.js style callback:
JavaScript try / catch 机制不能用来拦截由异步API产生的错误。一个初学者常犯的错误是尝试在Node.js风格的回调函数中使用抛出。
// This will not work
const fs = require('fs');
try {
fs.readFile('/some/file/that/does-not-exist', (err, data) => {
// mistaken assumption: throwing here...
if (err) {
throw err;
}
});
} catch(err) {
// This will not catch the throw!
console.log(err);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
This will not work because the callback function passed to fs.readFile() is called asynchronously. By the time the callback has been called, the surrounding code (including the try { } catch(err) { } block will have already exited. Throwing an error inside the callback can crash the Node.js process in most cases. If domains are enabled, or a handler has been registered with
process.on('uncaughtException')
, such errors can be intercepted.
它并不能正常工作,因为传递给fs.readFile()的回调函数会被异步地调用。等到回调函数被调用的时候,周围的代码(包括try { } catch(err) { } 代码块早都执行完了)。大多数情况下,在回调函数中抛出异常会导致Node.js进程崩溃。如果启用了域,或者已经注册了process.on('uncaughtException')
,这样的错误就会被截断。
Class: Error
A generic JavaScript Error object that does not denote any specific circumstance of why the error occurred. Error objects capture a “stack trace” detailing the point in the code at which the Error was instantiated, and may provide a text description of the error.
All errors generated by Node.js, including all System and JavaScript errors, will either be instances of, or inherit from, the Error class.
new Error(message)
Creates a new Error object and sets the error.message property to the provided text message. If an object is passed as message, the text message is generated by calling message.toString(). The error.stack property will represent the point in the code at which new Error() was called. Stack traces are dependent on V8’s stack trace API. Stack traces extend only to either (a) the beginning of synchronous code execution, or (b) the number of frames given by the property Error.stackTraceLimit, whichever is smaller.
Error.captureStackTrace(targetObject[, constructorOpt])
Creates a .stack property on targetObject, which when accessed returns a string representing the location in the code at which Error.captureStackTrace() was called.
const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack // similar to `new Error().stack`
- 1
- 2
- 3
The first line of the trace, instead of being prefixed with ErrorType: message, will be the result of calling targetObject.toString().
The optional constructorOpt argument accepts a function. If given, all frames above constructorOpt, including constructorOpt, will be omitted from the generated stack trace.
The constructorOpt argument is useful for hiding implementation details of error generation from an end user. For instance:
function MyError() {
Error.captureStackTrace(this, MyError);
}
// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame and all frames above it.
new MyError().stack
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
Error.stackTraceLimit
error.message
error.stack
Class: RangeError
Class: ReferenceError
Class: SyntaxError
Class: TypeError
Exceptions vs. Errors
System Errors
Class: System Error
error.code
error.errno
error.syscall
Common System Errors
文章来源: blog.csdn.net,作者:福州-司马懿,版权归原作者所有,如需转载,请联系作者。
原文链接:blog.csdn.net/chy555chy/article/details/52662171
- 点赞
- 收藏
- 关注作者
评论(0)