JavaScript崩溃指南:你遇到过这些异常吗?

今天让我们逐一详细罗列一下JavaScript的这些的错误类型,

  1. EvalError(eval错误)

    • EvalError ,通常用于表示与 eval() 函数相关的错误。eval() 函数用于在运行时执行动态生成的 JavaScript 代码。
    try {
        eval("alert('Hello, World!');");
    } catch (e) {
        console.error(e); // 抛出 EvalError: alert is not defined
    }
    
  2. RangeError(范围错误)

    • RangeError 表示一个值不在有效范围内的错误,通常涉及到数值超出了 JavaScript 的限制或范围。
    try {
        const arr = new Array(Infinity);
    } catch (e) {
        console.error(e); // 抛出 RangeError: Invalid array length
    }
    
  3. ReferenceError(引用错误)

    • ReferenceError 表示尝试引用未定义的变量或对象的错误。
    try {
        console.log(undefinedVariable);
    } catch (e) {
        console.error(e); // 抛出 ReferenceError: undefinedVariable is not defined
    }
    
  4. TypeError(类型错误)

    • TypeError 表示尝试在不支持的数据类型上执行操作或使用不允许的方法的错误。
    try {
        const number = 42;
        number.toUpperCase();
    } catch (e) {
        console.error(e); // 抛出 TypeError: number.toUpperCase is not a function
    }
    
  5. URIError(URI错误)

    • URIError 表示与 URI 相关的错误,通常涉及到对 URI 进行不正确的操作。
    try {
        decodeURIComponent('%');
    } catch (e) {
        console.error(e); // 抛出 URIError: URI malformed
    }
    
  6. SyntaxError(语法错误)

    • SyntaxError 表示代码包含语法错误,导致解析失败。这个错误类型通常由 JavaScript 引擎报告,WebIDL 中故意省略以保留给 ES 解析器使用。
    try {
        if (x > 10 {  // 抛出 SyntaxError: Unexpected token '{'
            // ...
        }
    } catch (e) {
        console.error(e);
    }
    
  7. Error(通用错误)

    • Error 是一个通用的错误类型,通常被用于创建自定义错误对象。
    try {
        throw new Error('This is a custom error.');
    } catch (e) {
        console.error(e); // 抛出 Error: This is a custom error.
    }
    
  8. IndexSizeError(索引不在允许的范围内)

    • IndexSizeError 表示尝试使用不在允许范围内的索引值的错误。
    try {
        const arr = [1, 2, 3];
        const item = arr.item(10); // 抛出 IndexSizeError: Index or size is negative or greater than the allowed amount
    } catch (e) {
        console.error(e);
    }
    
  9. HierarchyRequestError(节点树层次结构是不正确的)

    • HierarchyRequestError 表示尝试操作 DOM 节点树中的节点时,导致树的层次结构不正确的错误。
    try {
        const parent = document.createElement('div');
        const child = document.createElement('div');
        child.appendChild(parent); // 抛出 HierarchyRequestError: Failed to execute 'appendChild' on 'Node': The new child element contains the parent.
    } catch (e) {
        console.error(e);
    }
    
  10. InvalidCharacterError(字符串包含无效字符)

    • InvalidCharacterError 表示尝试使用无效字符的字符串进行操作时的错误。
    try {
        const invalidString = '\x01\x02\x03'; // 包含无效字符
        const element = document.createElement(invalidString); // 抛出 InvalidCharacterError: String contains an invalid character
    } catch (e) {
        console.error(e);
    }
    
  11. NoModificationAllowedError(对象不能被修改)

    • NoModificationAllowedError 表示尝试修改不允许修改的对象时的错误。
    try {
        const inputElement = document.createElement('input');
        inputElement.setAttribute('type', 'text'); // 抛出 NoModificationAllowedError: Cannot set attribute 'type' on readonly element.
    } catch (e) {
        console.error(e);
    }
    
  12. NotFoundError(对象不能在这里被找到)

    • NotFoundError 表示尝试查找不存在的对象时的错误。
    try {
        const element = document.querySelector('.nonexistent'); // 抛出 NotFoundError: An attempt was made to reference a Node in a context where it does not exist.
    } catch (e) {
        console.error(e);
    }
    
  13. NotSupportedError(不支持的操作)

    • NotSupportedError 表示尝试执行不被当前环境或对象支持的操作时的错误。
    try {
        navigator.vibrate([200, 100, 200]); // 尝试在不支持振动的环境中执行振动操作
    } catch (e) {
        console.error(e); // 抛出 NotSupportedError: Vibration API is not supported in this environment.
    }
    
  14. InvalidStateError(对象是一个无效的状态)

    • InvalidStateError 表示尝试在对象处于无效状态时执行操作的错误。
    try {
        const audioElement = document.createElement('audio');
        audioElement.play(); // 尝试在未加载音频的情况下播放音频
    } catch (e) {
        console.error(e); // 抛出 InvalidStateError: play() can only be initiated by a user gesture.
    }
    
  15. SyntaxError(字符串不匹配预期的模式)

    • SyntaxError 表示尝试使用不符合预期模式的字符串时的错误。
    try {
        JSON.parse("{'name': 'John'}"); // 使用单引号而不是双引号包围属性名
    } catch (e) {
        console.error(e); // 抛出 SyntaxError: Unexpected token ' in JSON at position 2
    }
    
  16. InvalidModificationError(对象不能以这种方式被修改)

    • InvalidModificationError 表示尝试以不允许的方式修改对象时的错误。
    try {
        const inputElement = document.createElement('input');
        inputElement.setAttribute('type', 'password'); // 尝试修改已创建的 input 元素的 type 属性
    } catch (e) {
        console.error(e); // 抛出 InvalidModificationError: Cannot set attribute 'type' on readonly element.
    }
    
  17. NamespaceError(操作在 XML 命名空间内不被允许)

    • NamespaceError 表示尝试在 XML 命名空间内执行不允许的操作时的错误。
    try {
        const xmlDocument = new DOMParser().parseFromString("<book></book>", "text/xml");
        const element = xmlDocument.createElement("author"); // 尝试在 XML 命名空间中创建元素
    } catch (e) {
        console.error(e); // 抛出 NamespaceError: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
    }
    
  18. InvalidAccessError(对象不支持这种操作或参数)

    • InvalidAccessError 表示尝试使用不支持的操作或参数访问对象时的错误。
    try {
        const canvas = document.createElement('canvas');
        canvas.getContext('webgl', { antialias: true }); // 尝试在不支持抗锯齿的情况下请求 WebGL 上下文
    } catch (e) {
        console.error(e); // 抛出 InvalidAccessError: Option 'antialias' is not supported by this context.
    }
    
  19. TypeMismatchError(对象的类型不匹配预期的类型)

    • TypeMismatchError 表示尝试将对象分配给不兼容的类型或参数时的错误。
    try {
        const inputElement = document.createElement('input');
        inputElement.value = {}; // 尝试将对象分配给 input 元素的 value 属性
    } catch (e) {
        console.error(e); // 抛出 TypeMismatchError: The provided value is not a string.
    }
    
  20. SecurityError(此操作是不安全的)

    • SecurityError 表示尝试执行被浏览器安全策略限制的不安全操作时的错误。
    try {
        const iframe = document.createElement('iframe');
        iframe.src = 'http://example.com'; // 尝试加载不安全的外部资源
    } catch (e) {
        console.error(e); // 抛出 SecurityError: Blocked a frame with origin "null" from accessing a cross-origin frame.
    }
    
  21. NetworkError(发生网络错误)

    • NetworkError 表示尝试执行网络请求或操作时发生的网络相关错误。
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://example.com/api/data', true);
    xhr.send();
    xhr.onerror = function () {
        console.error('NetworkError:', xhr.statusText); // 抛出 NetworkError: Failed to load
    };
    
  22. AbortError(操作被中止)

    • AbortError 表示尝试中止正在进行的操作时的错误。
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://example.com/api/data', true);
    xhr.send();
    xhr.abort();
    xhr.onerror = function () {
        console.error('AbortError:', xhr.statusText); // 抛出 AbortError: The operation was aborted.
    };
    
  23. URLMismatchError(给定的 URL 不匹配另一个 URL)

    • URLMismatchError 表示尝试将一个 URL 与另一个 URL 进行比较,但它们不匹配时的错误。
    const url1 = new URL('http://example.com');
    const url2 = new URL('http://example.org');
    if (url1.href !== url2.href) {
        console.error('URLMismatchError: URLs do not match.'); // 抛出 URLMismatchError
    }
    
  24. QuotaExceededError(已经超过给定配额)

    • QuotaExceededError 表示尝试在已达到或超过了指定配额时执行某些操作的错误。
    try {
        localStorage.setItem('key', 'value'); // 尝试存储数据,但已达到本地存储的容量配额
    } catch (e) {
        console.error(e); // 抛出 QuotaExceededError: The quota has been exceeded.
    }
    
  25. TimeoutError(操作超时)

    • TimeoutError 表示尝试执行的操作在超过指定的时间限制后仍未完成的错误。
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'http://example.com/api/slow', true);
    xhr.timeout = 5000; // 设置超时时间为5秒
    xhr.ontimeout = function () {
        console.error('TimeoutError: The operation timed out.'); // 抛出 TimeoutError
    };
    xhr.send();
    
  26. InvalidNodeTypeError(这个操作的节点或节点祖先是不正确的)

    • InvalidNodeTypeError 表示尝试执行操作的节点或节点祖先类型不正确的错误。
    try {
        const textNode = document.createTextNode('Text');
        textNode.appendChild(document.createElement('div')); // 尝试在文本节点上附加元素
    } catch (e) {
        console.error(e); // 抛出 InvalidNodeTypeError: Node cannot have children of type ELEMENT.
    }
    
  27. DataCloneError(对象不能克隆)

    • DataCloneError 表示尝试克隆对象失败的错误,通常在 Web Workers 等环境中使用。
    try {
        const worker = new Worker('worker.js');
        worker.postMessage({ complexObject: new Int32Array(10) }, [new Int32Array(10).buffer]); // 尝试传递不可克隆的对象
    } catch (e) {
        console.error(e); // 抛出 DataCloneError: The object could not be cloned.
    }
    ``
    
    
    
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zayyo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值