

JavaScript Error Handling with Try Catch | Bits and Pieces
source link: https://blog.bitsrc.io/javascript-try-catch-all-you-need-to-know-16b9ae08183b
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Error Handling with JavaScript Try Catch
JavaScript Try Catch: What You Need to Know
Have you ever made a mistake in your code that could not be executed afterward? Or have you sent a request to a server that failed and led to some unexpected consequences? Of course, you have — like so many of us.
Such errors have mysterious names and are called exceptions. You might wonder how best to deal with them. Every programming language gives us some tools for that, and JavaScript is no exception.
To address these errors in JavaScript, we’re going to learn how to use try/catch
.
Handling errors with JavaScript try catch
In general, the try/catch
block in JavaScript looks like this:
The try
block contains a set of statements where an exception can occur, and is always followed by a catch block, which handles the exception that occurs in the associated try block. The catch
block “catches” an error so that you can get more information about it by checking the properties of the error object.
In addition to the try/catch construction, the throw
keyword is also widely used in this context. By applying it, we can create our own customized exceptions. This makes our application and business logic more powerful, understandable, and, I’d say, human-readable.
The first real-world example off the top of my head is data validation:
In the code snippet, we’re trying to retrieve the token from the query property of the request. If there’s no token, or the value is empty, we’re literally “throwing” an error, which is caught by the catch
block and shown in the logs. Our exploration doesn’t stop here.
Since Error
is a class, it’s obviously possible to create our own error classes for the sake of clarity.
Check it out:
In this example, we’ve created our own ValidationError
class and used it for error handling of the specific business logic above. In the logs, it comes up as “Failed to authenticate ValidationError. Have not received [token]”
. Applying this technique, you can determine the error type and handle it differently:
Rethrowing an error
The last technique I will mention here is to rethrow an error. Use it when you need to handle an error on the upper stage, not inside a particular handler.
There’s a de facto standard according to which the error handler (or a particular catch block) should handle the error specifically related to it, while everything else should be rethrown further. In the end, there should be a default error handler that handles everything that was not caught by our gatekeepers (catch blocks):
Now, let’s refactor our code a bit. It’s better to move the validation code to a separate function for readability purposes:
Using the finally block
Sometimes, it might be required in cases of try/catch
and success/fail that there be some finalizing and independent action. The basic use case is as follows: a code opens a file descriptor; reads/processes data inside it; and, in case of an error or a successful completion, the file should be closed and resources released.
For this purpose, you can use the try/catch/finally
construction in JavaScript:
Note that all the aforementioned code is synchronous. In the modern JavaScript (ES2017 and later) try/catch/finally
can be fully used with async functions. For more detail, please see this tutorial.
Let’s assume that the authenticate function is async:
So, if the promise is rejected, the catch block will handle it in the same way as above.
Conclusion
One more piece of advice: try to avoid nested try/catch blocks. If you include them, your code probably violates the SRP. As a quick fix, you might try to move one of the blocks to a separate function.
Thanks for reading!
Originally posted at: https://anywhere.epam.com/en/blog/javascript-try-catch-all-you-need-to-know
Build applications differently
OSS Tools like Bit offer a new paradigm for building modern apps.
Instead of developing monolithic projects, you first build independent components. Then, you compose your components together to build as many applications as you like. This isn’t just a faster way to build, it’s also much more scalable and helps to standardize development.
It’s fun, give it a try →
Recommend
-
48
In this post, you'll learn how to use exception handling in PHP. As of PHP 5, we can use try catch blocks for error handling—this is a better way to handle exceptions and control the flow of your application. In this arti...
-
16
Namespace in JavaScript — The BasicsOrganized meaningful code...
-
19
Currying for JavaScript Developers with ExamplesWhat is currying? Practical examples of currying in JavaScript. Why currying is useful in programming. How to create curried functions.Have you...
-
8
JavaScript API for web applications to share content including images and videos. Take advantage of the powerful feature that has always been available to Android and iOS apps.Up and Running with the JavaScript Share API
-
10
JavaScript Prototype Chains and InheritanceExcerpt from JavaScript advanced programmingInheritance is one of the most talked about concepts in OO languages.Many OO languages suppor...
-
12
A Future Made of JavaScriptYou know that meme where they try to run Doom on anything electronic with a screen and some kin...
-
8
Creating Enums in Vanilla JavaScriptImage from unsplash.comLet’s start with a question: Can numbers represent the types of some subjects? Confusing, right?That’s okay because a nu...
-
9
JavaScript Interview Question: Explain OOP and FPWhat is Object-Oriented Programming? What is Functional Programming?Photo by
-
11
Blog / JavaScript / Error Handling in JavaScript: A Guide to Try/Catch, Throw, and Custom Error Classes Erro...
-
10
User Authentication with JavaScript and Express: A Practical GuideDelving into user verification, session management, and authentication strategies — with practical examples using JavaScript, Express,...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK