这篇文章主要介绍了JavaScript中的错误对象error object的示例分析,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
公司主营业务:成都做网站、成都网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。成都创新互联公司是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。成都创新互联公司推出昭化免费做网站回馈大家。
每当 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..."
}浏览器兼容性

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);
    }
}浏览器兼容性

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....
}浏览器兼容性

感谢你能够认真阅读完这篇文章,希望小编分享的“JavaScript中的错误对象error object的示例分析”这篇文章对大家有帮助,同时也希望大家多多支持创新互联,关注创新互联行业资讯频道,更多相关知识等着你来学习!
名称栏目:JavaScript中的错误对象errorobject的示例分析
网页地址:http://www.scyingshan.cn/article/jcdijp.html

 建站
建站
 咨询
咨询 售后
售后
 建站咨询
建站咨询 
 