Home  >  Article  >  Web Front-end  >  Introduction to JavaScript error handling mechanism (with examples)

Introduction to JavaScript error handling mechanism (with examples)

不言
不言forward
2018-10-19 15:29:431747browse

This article brings you an introduction to the JavaScript error handling mechanism (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Sometimes, in the tool function that you encapsulate, if no parameters are passed or parameters of the wrong type are passed in, some errors should be thrown as a warning; it will also be thrown if the framework is not used normally. If something goes wrong, if you don't know anything about the error, you won't be able to debug it. Based on the above, it is necessary to understand the error handling mechanism.

The following is the author's summary. If there are any errors, please point them out.

Error constructor
There are a total of 8 error type constructors in the JavaScript specification
Error -- error object
SyntaxError --parsing process syntax error
TypeError --not valid Type
ReferenceError -- Invalid reference
RangeError -- The value exceeds the valid range
URIError -- Error in parsing URI encoding
EvalError -- Error in calling eval function
InternalError -- Javascript engine internal error Exception thrown, "Too much recursion"

Two of them are specially explained:
EvalError is an error in calling the eval function and has been deprecated. For backward compatibility, lower versions can still be used.
InternalError throws an error if the recursion is too deep. Most browsers have not implemented it. It is a non-standard method and is disabled in the production environment.
Inheritance relationship
Error is the base class of errors. Other types inherit the Error class and can be used. Object.getPrototypeOf() provided in ES6 to determine whether a class inherits another class.

console.log(Object.getPrototypeOf(SyntaxError) === Error);    // true
console.log(Object.getPrototypeOf(TypeError) === Error);   // true
console.log(Object.getPrototypeOf(RangeError) === Error);   // true
console.log(Object.getPrototypeOf(URIError) ===  Error);   // true
console.log(Object.getPrototypeOf(EvalError) === Error);   // true
console.log(Object.getPrototypeOf(ReferenceError) === Error); // true

Let’s talk about the use of each error type and the error scenarios.

Error
An error object can be created through the Error constructor. When a runtime error occurs, an Error instance object will be thrown.
Syntax: new Error([message])
Parameters:

message 可选,错误描述信息。

Throw an error
Use the throw statement to throw an exception
throw new Error('What is thrown here is Error message')
After running, it will be printed on the console:
Uncaught Error: The error message is thrown here
Note: After using throw to throw an exception, the subsequent code will no longer be executed.

Capturing errors
You can capture this error through the try{}catch(){} statement

try{
   throw new Error('这里抛出的是错误信息')
 }
 catch(err){
   alert(err.name + ' '+ err.message)
   }

Attribute description:

 当使用new Error创建错误实例后,会有两个属性:

let e = new Error('What is thrown here is the error message');
name attribute is the type of error, this time it is Error
message attribute, which is the error message, this time it is 'thrown here' The error message is '

SyntaxError
Syntax error in the parsing process. There are many errors thrown by this type, which are often grammatical errors caused when writing, for example:

let n = 11;   // Uncaught SyntaxError: Invalid or unexpected token
let str = "hel"lo" // Uncaught SyntaxError: Unexpected identifier
let 123Var = 'hi' // Uncaught SyntaxError: Invalid or unexpected token

There are many syntax errors, so I won’t list them one by one. When running in the browser, the console will throw an error and tell you which line it is, so it is more convenient for the debugger to use it. But you need to understand the error type as SyntaxError and the error message that follows, so that you can easily correct the error.

TypeError
is not a valid type. This kind of error means that the type given is not the required type, resulting in inoperability and a type error will be thrown.
The variable or parameter is not of the expected type,
The variable or parameter is not of the expected type
For example, new must be followed by a function, and the given one is not a function, a type error will be thrown

let fn = 'hello';
new fn;

Throws an error:
Uncaught TypeError: fn is not a constructor
Calling a method that does not exist on an object

let obj = {};
obj.fn()

Throws an error:
Uncaught TypeError: obj.fn is not a function
Of course, you can also force the incoming parameters to be specified types when encapsulating the function, otherwise a type error will be thrown.

function flatten(arr){
if( !Array.isArray(arr) )
{
       throw new TypeError('传入参数不是数组')   
}    
}
flatten('test');

When the incoming parameter is not an array, a custom type error is thrown:
Uncaught TypeError: The incoming parameter is not an array

ReferenceError
Invalid reference.

References a variable that does not exist

console.log(a);

Throws an error
Uncaught ReferenceError: a is not defined
Assign a variable to a data that cannot be assigned a value
This mistake is often made when making a judgment in the if statement after calling a method. The comparison operator == is written as the assignment operator =. For example, judging whether the first character of a string is the specified character:

let str = 'hello';
if( str.charAt(0) = 'h' ){
   console.log('第一个字符为h');
   }

Throws error:
Uncaught ReferenceError: Invalid left-hand side in assignment
RangeError
The value is outside the valid range. In some methods, the value passed in must be within a certain range, otherwise an out-of-range error will be thrown.
The length passed in when creating the array is less than 0

let arr = new Array(-1)

Throws an error:
Uncaught RangeError: Invalid array length
The repeat method repeats the specified string the number of times it is repeated is less than 0

let str = 'hello';
str.repeat(-1)

Throws error:
Uncaught RangeError: Invalid count value

URIError
Error in processing URI encoding. The function parameters are incorrect, mainly the six functions encodeURI(), decodeURI(), encodeURIComponent(), decodeURIComponent(), escape() and unescape().
For example:

decodeURIComponent('%');
decodeURI('%2')

Throws an error:
Uncaught URIError: URI malformed

Custom error type
Sometimes you want to customize the error type , you need to customize a constructor, and then let the prototype inherit Error.prototype.

function MyErrorType(message){
this.message = message || '错误';
this.name = 'MyErrorType';
this.stack = (new Error()).stack;  // 错误位置和调用栈
}
MyErrorType.prototype = Object.create(Error.prototype);
MyErrorType.prototype.constructor = MyErrorType;
throw new MyErrorType('自定义错误类型抛出错误')

关于调用的错误栈信息
提供的错误的跟踪功能,以什么样的调用顺序,在哪个文件的哪一行捕获到这个错误。
例如以下调用:

 function trace() {
  try {
        throw new Error('myError');
  }
  catch(e) {
        console.log(e.stack);
  }
  }
function b() {
trace();
}
function a() {
b(3, 4, '\n\n', undefined, {});
}
a('first call, firstarg');

错误信息为:
Error: myError
  at trace (0c3d1a8a9fac89c933e63fe9a97ef2f1:3:14)
  at b (0c3d1a8a9fac89c933e63fe9a97ef2f1:10:6)
  at a (0c3d1a8a9fac89c933e63fe9a97ef2f1:13:6)
  at 0c3d1a8a9fac89c933e63fe9a97ef2f1:15:4
以上为抛错的构造函数的总结,如有误之处欢迎扶正。

The above is the detailed content of Introduction to JavaScript error handling mechanism (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete