logo icon

OKSANA

KOROBANOVA

macbook pro on persons lap
Back to all posts

Errors & Error Handling & Debugging

Some tips on errors & how to debug properly if you are a JS developer


Date:


Types of Errors in JavaScript

JavaScript errors can be broadly classified into three categories: syntax errors, runtime errors, and logical errors.

Syntax Errors

  • SyntaxError

A SyntaxError occurs when the code contains invalid syntax. Syntax errors are directly identified by the JavaScript parser during the compilation phase before the code is executed.

1// SyntaxError: Missing closing parenthesis
2console.log("Hello, world!";

Runtime Errors

  • ReferenceError

A ReferenceError occurs when trying to reference a variable that has not been declared.

1// ReferenceError: nonExistentVariable is not defined
2console.log(nonExistentVariable);

  • TypeError

A TypeError occurs when an operation is performed on a value of an inappropriate type. This can happen when trying to call a method on a non-object type or accessing properties on null or undefined.

1// TypeError: number is not a function
2let num = 42;
3num();

  • RangeError

A RangeError occurs when a value is not within the set or range of allowable values. This can happen with arrays, numbers, or when passing parameters to functions that expect a certain range.

1// RangeError: Invalid array length
2let arr = new Array(-1);

  • URIError

A URIError occurs when global URI handling functions are used inappropriately. These functions include decodeURI(), decodeURIComponent(), encodeURI(), and encodeURIComponent().

1// URIError: URI malformed
2decodeURIComponent('%');

  • EvalError

An EvalError is thrown when the eval() function is used incorrectly. This type of error is not commonly encountered as modern JavaScript engines rarely throw it.

1// EvalError: This error is not typically used in modern JavaScript
2eval('foo bar');

  • InternalError

An InternalError occurs when an internal error in the JavaScript engine itself is encountered. This is often related to resource constraints like stack overflow or excessive recursion.

1// InternalError: too much recursion (in some environments)
2function recurse() {
3    recurse();
4}
5recurse();

Logical Errors

Logical errors don’t have a specific error object in JavaScript but can be caused by incorrect logic in the code. They are often detected through testing and debugging rather than being thrown by the JavaScript engine.

Example: Incorrect conditions in if statements, wrong calculations, or flawed loops.

1let age = 18;
2// Logical error: incorrect comparison (should be == or ===)
3if (age = 21) {
4    console.log("You are an adult.");

Error Handling in JavaScript

JavaScript provides several mechanisms to handle errors gracefully, ensuring that applications remain robust and user-friendly.

Try-Catch Block: The try-catch block is used to handle runtime errors. Code that may throw an error is wrapped in a try block, and the catch block handles the error if it occurs.

1try {
2    let result = someFunction();
3    console.log(result);
4} catch (error) {
5    console.error("An error occurred: ", error.message);
6}

Throwing Errors: You can create and throw custom errors using the throw statement. This is useful for enforcing specific conditions and creating more meaningful error messages.

1function divide(a, b) {
2    if (b === 0) {
3        throw new Error("Division by zero is not allowed.");
4    }
5    return a / b;
6}
7
8try {
9    divide(4, 0);
10} catch (error) {
11    console.error(error.message);
12}

Finally Block: The finally block executes code after the try and catch blocks, regardless of whether an error occurred. This is useful for cleanup operations.

1try {
2    let data = fetchData();
3    process(data);
4} catch (error) {
5    console.error("Error processing data: ", error);
6} finally {
7    console.log("Cleanup operations");
8}

Promise Catch Method: For handling errors in asynchronous code using promises, the .catch method is used to handle any errors that occur during the promise's execution.

1fetch('https://api.example.com/data')
2    .then(response => response.json())
3    .then(data => console.log(data))
4    .catch(error => console.error("Fetch error: ", error));

Async/Await with Try-Catch: With the advent of async/await, error handling in asynchronous code can be managed using try-catch blocks, providing a more synchronous code flow.

1async function fetchData() {
2    try {
3        let response = await fetch('https://api.example.com/data');
4        let data = await response.json();
5        console.log(data);
6    } catch (error) {
7        console.error("Async/await error: ", error);
8    }
9}
10
11fetchData();

Debugging

Here I will share a video from Web Dev Simplified