每當 JavaScript 中發生任何執行時間錯誤時,都會引發Error
物件。在許多情況下,我們還可以擴展這些標準Error
對象,以建立我們自己的自訂Error
對象。
屬性
Error
物件具有2個屬性
#name -設定或傳回錯誤名稱。具體來說,它傳回錯誤所屬的建構函數的名稱。
它有6個不同的值-EvalError
,RangeError
,ReferenceError
,TypeError
,SyntaxError
,URIError
。我們將在本文後面討論這些內容,這些所有錯誤類型均繼承自Object-> Error-> RangeError
。
message-設定或傳回錯誤訊息
#範例
1.通用的錯誤
我們可以使用Error
物件建立一個新的Error
,然後使用throw
關鍵字明確拋出該錯誤。
try{ throw new Error('Some Error Occurred!') } catch(e){ console.error('Error Occurred. ' + e.name + ': ' + e.message) }
2.處理特定的錯誤類型
我們也可以使用以下的instanceof
關鍵字來處理特定的錯誤類型。
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.自訂錯誤類型
我們也可以透過建立繼承Error
物件的類別來定義自己的錯誤類型。
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 }
瀏覽器相容性
#Error 的物件類型
現在讓我們討論可用於處理不同錯誤的不同錯誤物件類型。
1. EvalError
建立一個error
實例,表示錯誤的原因:與 eval()
有關。
這裡要注意的一點是,目前ECMAScript規格不支援它,並且在運行時不會將其拋出。取而代之的是,我們可以使用SyntaxError
錯誤。但是,它仍然可以與ECMAScript的早期版本向後相容。
語法
new EvalError([message[, fileName[, lineNumber]]])
範例
##
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..." }
瀏覽器相容性
error實例,表示錯誤的原因:數值變數或參數超出其有效範圍。
new RangeError([message[, fileName[, lineNumber]]])
下面的情况会触发该错误:
1)根据String.prototype.normalize()
,我们传递了一个不允许的字符串值。
// Uncaught RangeError: The normalization form should be one of NFC, NFD, NFKC, NFKD String.prototype.normalize(“-1”)
2)使用Array
构造函数创建非法长度的数组
// RangeError: Invalid array length var arr = new Array(-1);
3)诸如 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;
显式抛出ReferenceError
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
创建一个error实例,表示错误的原因:eval()在解析代码的过程中发生的语法错误。
换句话说,当 JS 引擎在解析代码时遇到不符合语言语法的令牌或令牌顺序时,将抛出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,}');
创建一个SyntaxError
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
创建一个error实例,表示错误的原因:变量或参数不属于有效类型。
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
捕获TypeError
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 }
创建 TypeError
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
创建一个error实例,表示错误的原因:给 encodeURI(
)或 decodeURl()
传递的参数无效。
如果未正确使用全局URI处理功能,则会发生这种情况。
简单来说,当我们将不正确的参数传递给encodeURIComponent()或
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")
捕捉URIError
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... }
显式抛出URIError
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.... }
浏览器兼容性
英文原文地址:http://help.dottoro.com/ljfhismo.php
作者:Isha Jauhari
更多编程相关知识,请访问:编程视频!!
以上是JavaScript中的錯誤物件(Error object)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

Dreamweaver CS6
視覺化網頁開發工具

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版
好用的JavaScript開發工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。