Managing errors and debugging your code in Javascript is one of the ways we make sure our code works. In this article, we'll look at common ways we can debug and manage errors in our code.
Consoles
Console logs are the best way we can check what's happening in our code. Console logs can be viewed in most browsers by right clicking anywhere on a webpage, and selecting "Inspect Element". In the console tab, we can see any console logs from our Javascript code.
To add a console log to your code, the easiest way is to do the following:
console.log("Hello!");
If this code runs from our Javascript, then we will see "Hello" in our code. This is the most basic way to log errors or messages, but there are others.
Other Useful Consoles
We can use console logs to manage how errors and messages appear in our code. Let's look at how that works.
Console Errors
Errors are usually styled differently in consoles and show that something significant has broken. Typically these are styled in red. This will not stop execution of the rest of your code. We can show an error message using console.error:
console.error("ERROR!");
Console Warnings
Similar to errors, but typically in yellow to warn the user that expected behaviour may have changed. Again, these do not stop execution, and can be run as follows:
console.warning("warning!");
Timing with Consoles
Figuring out how long an operation takes to do can be important in highly optimised systems. To do that we have a number of console operations we can use:
console.time("my timer");
console.timeLog("my timer");
console.timeEnd("my timer");
In the above, we have one timer which we start called "my timer". We can then log times against "my timer", or end it altogether. In more detail, these do the following things:
-
console.time
- this starts a timer which will run in the background called "my timer". You can have up to 10,000 timers. -
console.timeLog
- this will log the time for "my timer" at that specific point in the code since the timer started. -
console.timeEnd
- this will end "my timer" completely, so we won't be able to log times against it. It will also log the time.Errors in Javascript
There are a number of different errors Javascript can give us, which will tell us something about what we've done wrong:
ReferenceError
- we tried to reference a variable that did not exist.EvalError
- an issue happened while we tried to run eval().TypeError
- an issue happened due to something relating to type - i.e. a function was expecting one type, and got another.RangeError
- an issue happened as we tried to call something outside the range of what was expected, i.e. we called an array element which did not exist.AggregateError
- an error which contains many errors.-
URIError
- we have an invalid URI string or have used a URI function incorrectly.Avoiding Breaking Errors
These errors all tell us something about why our code is invalid. We can avoid errors by writing good quality code, and using conditional statements to ensure variables are valid. For example, we could check the typeof a variable is defined, before we use it:
let i = 1;
if(typeof i !== "undefined") {
i += 20;
}
Checking variables exist is a common way to avoid errors - especially if we know the variable might not exist, i.e. if it is coming from an API or external source.
Try ... Catch
Another way to avoid errors is to use try ... catch statements. The errors we mentioned in the "Errors in Javascript" section are all code breaking - that means the code will stop working if they are thrown. With try ... catch statements, we can try some code, and if it fails, we catch the error. If the error was code breaking, it will no longer break the code, and we'll simply get a info message in the console log.
Such a statement may look like this:
try {
// This throws an error since i is not defined.
i += 20;
} catch(error) {
// We can catch the error so the code will not break, and console log it.
console.log(error);
}
try ... catch
statements become very important when we try to build Node.JS servers. If a code breaking error is thrown, it can crash the entire server - so we need to catch and handle our errors appropriately, as to not break the experience for everyone.
Handling Specific Errors with Try ... Catch
If we want to handle a specific error, we can catch it and check it using the instanceof
property. That looks something like this:
try {
// This throws an error since i is not defined.
i += 20;
} catch(error) {
// We can catch the error so the code will not break, and console log it.
if(error instanceof ReferenceError) {
console.log("This is a reference error");
} else if(error instanceof EvalError) {
console.log("This was an error with the eval() function");
}
}
This lets us take specific actions for specific errors, so we can give the user a better experience.
Generating our own errors
Imagine some code where we need a variable to exist, or the rest of the code will break. We might want to generate our own errors, to stop the code from executing. We can do this with the throw keyword, where the text after throw is the message we want the user to get. For example:
if(typeof i == "undefined") {
throw "Could not find variable i";
}
This error will throw a message like this:
Uncaught Could not find variable i
We can even use numbers, objects or booleans as our error messages. Using this technique, we can also create a new error object, with specific messages:
throw new Error("You made an error");
This will give us a message which looks something like this:
Uncaught Error: You made an error at anonymous:1:7
Conclusion
Thanks for reading this guide to Javascript errors. Proper error message is really important in any language, and Javscript is no exception (pun intended). In this guide we've covered:
- The different types of console logs in Javascript, including warnings and errors.
- How to time an operation using the console, to potentially optimise your code.
- How to catch errors so they don't break your entire application.
- How to give specific messages based on types of errors using the
instanceof
command.
Top comments (0)