in

How to handle errors in JavaScript

pexels alleksana 4271933

[ad_1]

Programming errors are inevitable. Sooner or later, your application will experience unexpected behavior. Like any programming language, JavaScript raises errors when something goes wrong in your code.


Errors interrupt the normal flow of your application. But it also helps protect your application from unpredictable behavior. Knowing how to properly handle errors is very important.

Why error handling is important

Error handling contributes to a better user experience. You can replace JavaScript’s default errors, and sometimes detailed errors, with your own more human-readable error message. It can gracefully handle the source of some errors and keep the program running rather than terminating.

Error handling is also useful during development. You can catch runtime errors and do something useful, like log them to the browser console. This is better than an error that causes a crash and you don’t know where or why it happened.

Structure of JavaScript built-in errors

A JavaScript error is an object with three properties:

  • name: This is the name of the error. For example, a missing variable name will throw a SyntaxError.
  • message: This is the body of the message and provides a textual description of the error.
  • cause: This property can be used in custom errors to trace the call stack.

Common types of errors in JavaScript

Here are some common errors in JavaScript.

syntax error

Syntax errors can occur when JavaScript tries to interpret your code. An error occurs if the code does not conform to the correct syntax. Common errors that can lead to syntax errors are:

  • Missing variable name.
  • Missing “}” after function.
  • Missing “)” after condition.

reference error

A reference error occurs when your program tries to reference a variable that is not available or out of scope.

TypeError

JavaScript can throw a type error when an operation cannot be performed because the expected type is different from the received type.

URI error

This error occurs when you use the global URI handling functions (such as decodeURIComponent()) incorrectly. As a result, encoding or decoding fails.

AggregateError

This error is used to represent multiple errors grouped together. Use when you want to throw many errors at once. For example, Promise.any() can throw AggregateError() when all promises passed to it are rejected.

internal error

An InternalError is thrown when an error occurs within the JavaScript engine.

range error

Some functions determine the range of values ​​that can be passed as arguments. This error will occur if you try to pass a value that is not in that range.

Error handling with Try…Catch blocks

JavaScript provides built-in exception handling functionality. Try… Catch… Finally block. You can also raise your own errors using throw operator.

You can use try…catch blocks to handle errors that occur at runtime. Write valid code in the try block that is expected to run correctly. A catch block allows you to write error handling code.

 try {
    
} catch (error) {
    
} finally {
    
}

If the code inside the try block does not raise an error, the catch block is ignored. If an error occurs, execution jumps to the catch block. The code inside the finally block is executed regardless of whether an error occurs. This block is not required and can be omitted if not required.

The code you include in the try block must be valid. Otherwise JavaScript will throw a parse error.

Let’s see a real example.

 try {
    console.log(text)
} catch (error) {
    console.log(error.message)
} finally {
    console.log("Will be executed regardless")
}

This program tries to record the value of a text variable. The program throws an error because that variable is not defined. This error is printed in the console catch block. The finally block is then executed and prints its own message.

 ReferenceError: text is not defined
Will be executed regardless

In situations where you need to raise your own error, throw operator.

Consider the following example which throws an error if the data is false.

 const data = getData()

try {
    if (!data) {
        throw "No data"
    }

    console.log(data)
    
} catch(error) {
    console.log(error)
}

In this example, the program calls the getData() function and assigns the result to a data variable. In the try block, the block throws a custom error if the data is empty. The catch block catches that error and logs it to the console.

Throwing errors is very useful during development. Use custom error messages to understand why your application isn’t working as expected.

As this example shows, you can use strings for error objects. In fact, any JavaScript expression can be thrown as an error. However, for consistency with built-in errors, use a JavaScript object containing the name and message.

 throw {
    name: "Error name",
    message: "Error message"
}

You can also use JavaScript’s built-in constructors when throwing errors. These constructors include Error, SyntaxError, ReferenceError, and so on.

To throw an error using the Error constructor, use the following code.

 throw new Error("No data")

You can now see the name and message.

 console.log(error.name) 
console.log(error.message)

Extending the JavaScript error object

Custom error classes are useful for handling errors that don’t correspond to the objects already provided by JavaScript. For example, you might want to isolate data validation errors as a specific type called ValidationError.

You can create custom error classes using JavaScript ES2015 classes.

 class ValidationError extends Error {
    constructor(message) {
        super(message);
        this.name = "ValidationError";
    }
}

Throw an error using the ValidationError class like this:

 throw new ValidationError("Your error message")

The thrown error will be an object with a value of name and message.

 {
    name: "ValidationError",
    message: "Your error message"
}

error helps

Error handling is a fundamental part of programming, regardless of the language you’re using. JavaScript has great support for raising and catching errors in the style of exceptions. There are also some built-in error types that you can handle and use in your own cases.

When writing JavaScript in “sloppy mode” some errors, such as syntax errors, may go undetected. Strict mode allows JavaScript to catch errors it would otherwise ignore.

[ad_2]

Source link

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *

GIPHY App Key not set. Please check settings

    025df02e5de37f54d1777d24445aedb7 M

    Healed by Grace: Amy’s Abortion Story

    Aaron Dunn new smsf

    Director identifies ‘silent compliance bomb’