Home>Article>Web Front-end> Error object in JavaScript
Whenever any runtime error occurs in JavaScript, anError
object is raised. In many cases, we can also extend these standard Errorobjects to create our own custom Error
objects.Properties
The object has 2 properties
- Set or return the error name. Specifically, it returns the name of the constructor to which the error belongs.It has 6 different values -
EvalError,RangeError
,ReferenceError
,TypeError
,SyntaxError
,URIError
. As we'll discuss later in this article, all error types inherit fromObject-> Error-> RangeError
.
-Set or return error message
Example
1. Common errorsWe can use the
Errorobject to create a newError
and then explicitly throw the error using thethrow
keyword.
try{ throw new Error('Some Error Occurred!') } catch(e){ console.error('Error Occurred. ' + e.name + ': ' + e.message) }2. Handle specific error types
We can also use the following
instanceofKeywords to handle specific error types.
try{ someFunction() } catch(e){ if(e instanceof EvalError) { console.error(e.name + ': ' + e.message) } else if(e instanceof RangeError) { console.error(e.name + ': ' + e.message) } // ... something else }3. Custom error types
We can also define our own by creating a class that inherits the
Errorobject error type.
class CustomError extends Error { constructor(description, ...params) { super(...params) if(Error.captureStackTrace){ Error.captureStackTrace(this, CustomError) } this.name = 'CustomError_MyError' this.description = description this.date = new Date() } } try{ throw new CustomError('Custom Error', 'Some Error Occurred') } catch(e){ console.error(e.name) //CustomError_MyError console.error(e.description) //Custom Error console.error(e.message) //Some Error Occurred console.error(e.stack) //stacktrace }Browser Compatibility
Object type of Error
1. EvalError
instance to indicate the cause of the error: related toeval()
.One thing to note here is that it is not supported by the current ECMAScript specification and will not be thrown by the runtime. Instead, we can use the
error. However, it remains backwards compatible with earlier versions of ECMAScript.
new EvalError([message[, fileName[, lineNumber]]])Example
try{ throw new EvalError('Eval Error Occurred'); } catch(e){ console.log(e instanceof EvalError); // true console.log(e.message); // "Eval Error Occurred" console.log(e.name); // "EvalError" console.log(e.stack); // "EvalError: Eval Error Occurred..." }Browser Compatibility
2. RangeError
Instance, indicating the cause of the error: the numerical variable or parameter exceeds its valid range. 下面的情况会触发该错误: 1)根据
2)使用
3)诸如
事例 对于数值
对于非数值
浏览器兼容性
创建一个
事例
显式抛出ReferenceError
浏览器兼容性 创建一个error实例,表示错误的原因:eval()在解析代码的过程中发生的语法错误。 换句话说,当 JS 引擎在解析代码时遇到不符合语言语法的令牌或令牌顺序时,将抛出 捕获语法错误
创建一个SyntaxError
浏览器兼容性
创建一个error实例,表示错误的原因:变量或参数不属于有效类型。
下面情况会引发 例如:
捕获TypeError
创建 TypeError
浏览器兼容性 创建一个error实例,表示错误的原因:给 如果未正确使用全局URI处理功能,则会发生这种情况。 简单来说,当我们将不正确的参数传递给encodeURIComponent()
捕捉URIError
显式抛出URIError
浏览器兼容性 英文原文地址:http://help.dottoro.com/ljfhismo.php 作者:Isha Jauhari 更多编程相关知识,请访问:编程视频!! The above is the detailed content of Error object in JavaScript. For more information, please follow other related articles on the PHP Chinese website!new RangeError([message[, fileName[, lineNumber]]])
String.prototype.normalize()
,我们传递了一个不允许的字符串值。// Uncaught RangeError: The normalization form should be one of NFC, NFD, NFKC, NFKD String.prototype.normalize(“-1”)
Array
构造函数创建非法长度的数组// RangeError: Invalid array length var arr = new Array(-1);
Number.prototype.toExponential()
,Number.prototype.toFixed()
或Number.prototype.toPrecision()
之类的数字方法会接收无效值。// Uncaught RangeError: toExponential() argument must be between 0 and 100 Number.prototype.toExponential(101) // Uncaught RangeError: toFixed() digits argument must be between 0 and 100 Number.prototype.toFixed(-1) // Uncaught RangeError: toPrecision() argument must be between 1 and 100 Number.prototype.toPrecision(101)
function checkRange(n) { if( !(n >= 0 && n <= 100) ) { throw new RangeError("The argument must be between 0 and 100."); } }; try { checkRange(101); } catch(error) { if (error instanceof RangeError) { console.log(error.name); console.log(error.message); } }
function checkJusticeLeaque(value) { if(["batman", "superman", "flash"].includes(value) === false) { throw new RangeError('The hero must be in Justice Leaque...'); } } try { checkJusticeLeaque("wolverine"); } catch(error) { if(error instanceof RangeError) { console.log(error.name); console.log(error.message); } }
3. ReferenceError
error
实例,表示错误的原因:无效引用。new ReferenceError([message[, fileName[, lineNumber]]])
ReferenceError
被自动触发。try { callJusticeLeaque(); } catch(e){ console.log(e instanceof ReferenceError) // true console.log(e.message) // callJusticeLeaque is not defined console.log(e.name) // "ReferenceError" console.log(e.stack) // ReferenceError: callJusticeLeaque is not defined.. } or as simple as a/10;
try { throw new ReferenceError('Reference Error Occurred') } catch(e){ console.log(e instanceof ReferenceError) // true console.log(e.message) // Reference Error Occurred console.log(e.name) // "ReferenceError" console.log(e.stack) // ReferenceError: Reference Error Occurred. }
4. SyntaxError
SyntaxError
。try { eval('Justice Leaque'); } catch(e){ console.error(e instanceof SyntaxError); // true console.error(e.message); // Unexpected identifier console.error(e.name); // SyntaxError console.error(e.stack); // SyntaxError: Unexpected identifier } let a = 100/; // Uncaught SyntaxError: Unexpected token ';' // Uncaught SyntaxError: Unexpected token ] in JSON JSON.parse('[1, 2, 3, 4,]'); // Uncaught SyntaxError: Unexpected token } in JSON JSON.parse('{"aa": 11,}');
try { throw new SyntaxError('Syntax Error Occurred'); } catch(e){ console.error(e instanceof SyntaxError); // true console.error(e.message); // Syntax Error Occurred console.error(e.name); // SyntaxError console.error(e.stack); // SyntaxError: Syntax Error Occurred }
5. TypeError
new TypeError([message[, fileName[, lineNumber]]])
TypeError
:
const a = 10; a = "string"; // Uncaught TypeError: Assignment to constant variable null.name // Uncaught TypeError: Cannot read property 'name' of null
try { var num = 1; num.toUpperCase(); } catch(e){ console.log(e instanceof TypeError) // true console.log(e.message) // num.toUpperCase is not a function console.log(e.name) // "TypeError" console.log(e.stack) // TypeError: num.toUpperCase is not a function }
try { throw new TypeError('TypeError Occurred') } catch(e){ console.log(e instanceof TypeError) // true console.log(e.message) // TypeError Occurred console.log(e.name) // TypeError console.log(e.stack) // TypeError: TypeError Occurred }
6. URIError
encodeURI(
)或decodeURl()
传递的参数无效。或
decodeURIComponent()函数时,就会引发这种情况。
new URIError([message[, fileName[, lineNumber]]])
encodeURIComponent()
通过用表示字符的UTF-8编码的一个,两个,三个或四个转义序列替换某些字符的每个实例来对URI进行编码。// "https%3A%2F%2Fmedium.com%2F" encodeURIComponent('https://medium.com/');
decodeURIComponent()
——对之前由encodeURIComponent
创建的统一资源标识符(Uniform Resource Identifier, URI)组件进行解码。// https://medium.com/ decodeURIComponent("https%3A%2F%2Fmedium.com%2F")
try { decodeURIComponent('%') } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // URI malformed console.log(e.name) // URIError console.log(e.stack) // URIError: URI malformed... }
try { throw new URIError('URIError Occurred') } catch (e) { console.log(e instanceof URIError) // true console.log(e.message) // URIError Occurred console.log(e.name) // "URIError" console.log(e.stack) // URIError: URIError Occurred.... }