百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> JavaScript中的错误对象(Error object)
分享文章到:

JavaScript中的错误对象(Error object)

发布时间:01/01 来源:未知 浏览: 关键词:

每当 JavaScript 中发生任何运转时错误时,都会激发Error对象。 在很多状况下,我们还可以扩展这些标准Error对象,以创立我们本人的自定义Error对象。

属性

Error 对象具有2个属性

name ——设定或返回错误名称。详细来说,它返回错误所属的结构函数的名称。

它有6个不一样的值-EvalErrorRangeErrorReferenceErrorTypeErrorSyntaxErrorURIError。 我们将在本文后面计议这些内容,这些所有错误类型均继承自Object-> Error-> RangeError

message-设定或返回错误新闻

1.png

事例

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
}

阅读器兼容性

2.png

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..."
}

阅读器兼容性

3.png

2. RangeError

创立一个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);
    }
}

阅读器兼容性

4.png

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.
}

阅读器兼容性

5.png

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
}

阅读器兼容性

6.png

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
}

阅读器兼容性

7.png

6. URIError

创立一个error实例,表示错误的缘由:给 encodeURI()或 decodeURl()传递的参数无效。

假如未准确使用全局URI处置功效,则会发生这种状况。

8.png

简便来说,当我们将不准确的参数传递给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....
}

阅读器兼容性

9.png

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有150人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板