Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the method of removing try-catch by Dima in ​ javascript

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what is the method of removing try-catch from Dima in javascript". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "what is the method of removing try-catch from Dima in javascript"?

The method of removing try-catch by Dima

Of course, the routine remains the same, Dima talks about callback hell, Promise chain and finally leads to async/await. When dealing with errors, he does not like the way of try-catch, so he wrote a to (promise) to encapsulate Promise, supplemented by deconstruction syntax, and realized the code written synchronously but similar to the Node error standard. The excerpt code is as follows

/ / to.js export default function to (promise) {return promise. Then (data = > {return [null, data];}) .catch (err = > [err]);}

Application example:

Import to from ". / to.js"; async function asyncTask (cb) {let err, user, savedTask; [err, user] = await to (UserModel.findById (1)); if (! user) return cb ("No user found"); [err, savedTask] = await to (TaskModel ({userId: user.id, name: "Demo Task"}); if (err) return cb ("Error occurred while saving task") If (user.notificationsEnabled) {const [err] = await to (NotificationService.sendNotification (user.id, "Task Created")); if (err) return cb ("Error while sending notification");} cb (null, savedTask);}

Dima's approach gives people a familiar feeling, isn't it often written in Node callbacks?

(err, data) = > {if (err) {/ / deal with error} else {/ / deal with data}}

So this method is really interesting. In retrospect, however, whenever an error is encountered in this code, the error message is pushed out through the cb () call, interrupting the rest of the process. This kind of interrupt error handling is actually suitable for try-catch.

Rewrite the above code using try-catch

To rewrite the above code with try-catch, first remove the to () encapsulation. In this way, if an error occurs, you need to use Promise.prototype.catch () to capture, or use try-catch to capture the await promise statement. What is captured is, of course, the err from reject in each business code.

Note, however, that instead of using err directly in the above code, you use custom error messages. So the err from reject needs to be further processed into the specified error message. Of course, it's not difficult for anyone, such as

SomeAsync () .catch (err = > Project.reject ("specified message"))

Then add try-catch to the outermost layer. So the rewritten code is:

Async function asyncTask (cb) {try {const user = await UserModel.findById (1) .catch (err = > Promise.reject ("No user found")); const savedTask = await TaskModel ({userId: user.id, name: "Demo Task"}) .catch (err = > Promise.reject ("Error occurred while saving task")) If (user.notificationsEnabled) {await NotificationService.sendNotification (user.id, "Task Created") .catch (err = > Promise.reject ("Error while sending notification"));} cb (null, savedTask);} catch (err) {cb (err);}}

The above code, in terms of code volume, does not reduce the amount of work compared to the Dima code, but removes a lot of if (err) {} structure. Programmers who are not used to using try-catch can't find a breakpoint, but programmers who are used to try-catch know that when an error occurs in the business process (reject in asynchronous code), the code will jump to the catch block to process the value from reject.

However, the information from the general business code reject is usually useful. If the err from each of the above business reject is itself an error message, then, using the Dima pattern, you still need to write

If (err) return cb (err)

Using the try-catch model, it's much easier.

Async function asyncTask (cb) {try {const user = await UserModel.findById (1); const savedTask = await TaskModel ({userId: user.id, name: "Demo Task"}); if (user.notificationsEnabled) {await NotificationService.sendNotification (user.id, "Task Created");} cb (null, savedTask);} catch (err) {cb (err) }}

Why? Because in Dima mode, if (err) actually handles two businesses: one is to capture the err that will cause an interruption and convert it into an error message, and the other is to interrupt the business process through return. So when the process of converting err to an error message is no longer needed, the handler who catches the interrupt and then causes the interrupt again becomes redundant.

Continue to improve

Improving try-catch Logic with functional expressions

Of course, there is room for improvement, such as the long code in the try {} block, which makes it difficult to read, and the logic of try-catch feels "cut off". In this case, you can use function expressions to improve

Async function asyncTask (cb) {async function process () {const user = await UserModel.findById (1); const savedTask = await TaskModel ({userId: user.id, name: "Demo Task"}); if (user.notificationsEnabled) {await NotificationService.sendNotification (user.id, "Task Created");} return savedTask;} try {cb (null, await process ()) } catch (err) {cb (err);}}

If the error handling code is long, it can also be written as a separate function expression.

What if the error handling logic of each step in the process is different?

What if an error occurs and is no longer converted to an error message, but to a specific error handling logic?

Think about it. We use strings to represent error messages, which can be handled later by console.log (). And logic, the most suitable representation is, of course, function expressions, which can eventually be handled uniformly through calls.

Async function asyncTask (cb) {async function process () {const user = await UserModel.findById (1) .catch (err = > Promise.reject (() = > {/ / deal with error on looking for the user return "No user found";})) Const savedTask = await TaskModel ({userId: user.id, name: "Demo Task"}) .catch (err = > Promise.reject () = > {/ / making model error / / deal with it return err = 1? "Error occurred while saving task": "Error occurred while making model";}); if (user.notificationsEnabled) {await NotificationService.sendNotification (user.id, "Task Created") .catch (err = > Promise.reject (() = > {/ / just print a message logger.log (err)) Return "Error while sending notification";} return savedTask;} try {cb (null, await process ());} catch (func) {cb (func ());}}

It can even deal with more complex situations.

You should all know .catch (err = > Promise.reject (xx)) by now, where the xx is the object captured by the catch block of try-catch, so if different business reject comes out with different objects, such as functions (representing error handling logic), strings (representing error messages), and numbers (representing error codes)-- you just need to change the catch block.

Try {/ /...} catch (something) {switch (typeof something) {case "string": / / show message something break; case "function": something (); break Case "number": / / look up something as code / / and show correlative message break; default: / / deal with unknown error}} at this point, I believe you have a deeper understanding of "what is the method of removing try-catch by Dima in javascript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report