search
HomeWeb Front-endJS TutorialError object in JavaScript

Error object in JavaScript

Jan 28, 2021 pm 07:15 PM
javascript

Error object in JavaScript

Whenever any runtime error occurs in JavaScript, an Error object is raised. In many cases, we can also extend these standard Error objects to create our own custom Error objects. Properties

Error

The object has 2 properties

name

- 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 from Object-> Error-> RangeError.

message

-Set or return error message

Error object in JavaScriptExample

1. Common errors

We can use the

Error

object to create a new Error and then explicitly throw the error using the throw 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

instanceof

Keywords 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

Error

object 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

Error object in JavaScriptObject type of Error

Now let us discuss the different error object types that can be used to handle different errors.

1. EvalError

Create an

error

instance to indicate the cause of the error: related to eval(). 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

SyntaxError

error. However, it remains backwards compatible with earlier versions of ECMAScript.

Grammar

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

Error object in JavaScript2. RangeError

Create an

error

Instance, indicating the cause of the error: the numerical variable or parameter exceeds its valid range. <p><span type="button" class="copyCode code-tool" data-toggle="tooltip" data-placement="top" data-clipboard-text="new RangeError([message[, fileName[, lineNumber]]]) " title="" data-original-title="复制"></span></p><pre class='brush:php;toolbar:false;'>new RangeError([message[, fileName[, lineNumber]]])</pre><p>下面的情况会触发该错误:</p> <p>1)根据<code>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(&#39;The hero must be in Justice Leaque...&#39;);
    }
}
try
{
    checkJusticeLeaque("wolverine");
}
catch(error)
{
    if(error instanceof RangeError)
    {
        console.log(error.name);
        console.log(error.message);
    }
}

浏览器兼容性

Error object in JavaScript

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(&#39;Reference Error Occurred&#39;)
} 
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.
}

浏览器兼容性

Error object in JavaScript

4. SyntaxError

创建一个error实例,表示错误的原因:eval()在解析代码的过程中发生的语法错误。

换句话说,当 JS 引擎在解析代码时遇到不符合语言语法的令牌或令牌顺序时,将抛出SyntaxError

捕获语法错误

try {
  eval(&#39;Justice Leaque&#39;);  
} 
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 &#39;;&#39;
// Uncaught SyntaxError: Unexpected token ] in JSON
JSON.parse(&#39;[1, 2, 3, 4,]&#39;); 
// Uncaught SyntaxError: Unexpected token } in JSON
JSON.parse(&#39;{"aa": 11,}&#39;);

创建一个SyntaxError

try {
  throw new SyntaxError(&#39;Syntax Error Occurred&#39;);
} 
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
}

浏览器兼容性

Error object in JavaScript

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 &#39;name&#39; 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(&#39;TypeError Occurred&#39;) 
} 
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
}

浏览器兼容性

Error object in JavaScript

6. URIError

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

如果未正确使用全局URI处理功能,则会发生这种情况。

Error object in JavaScript

简单来说,当我们将不正确的参数传递给encodeURIComponent()decodeURIComponent()函数时,就会引发这种情况。

new URIError([message[, fileName[, lineNumber]]])

encodeURIComponent()通过用表示字符的UTF-8编码的一个,两个,三个或四个转义序列替换某些字符的每个实例来对URI进行编码。

// "https%3A%2F%2Fmedium.com%2F"
encodeURIComponent(&#39;https://medium.com/&#39;);

decodeURIComponent()——对之前由encodeURIComponent创建的统一资源标识符(Uniform Resource Identifier, URI)组件进行解码。

// https://medium.com/
decodeURIComponent("https%3A%2F%2Fmedium.com%2F")

捕捉URIError

try {
  decodeURIComponent(&#39;%&#39;)
} 
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(&#39;URIError Occurred&#39;)
} 
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....
}

浏览器兼容性

Error object in JavaScript

英文原文地址: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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.