Welcome to the Linux Foundation Forum!

Chapter 10: "Handling Errors" errata

"Try/Catch" subsection

Erroneous invocation of result() in the code snippets below:

  1. try {
  2. const result = doTask(4)
  3. result()
  4. console.log('result', result)
  5. } catch (err) {
  6. if (err instanceof TypeError) {
  7. console.error('wrong type')
  8. } else if (err instanceof RangeError) {
  9. console.error('out of range')
  10. } else if (err.code === 'ERR_MUST_BE_EVEN') {
  11. console.error('cannot be odd')
  12. } else {
  13. console.error('Unknown error', err)
  14. }
  15. }
  16.  
  17. try {
  18. const result = doTask(4)
  19. result()
  20. console.log('result', result)
  21. } catch (err) {
  22. if (err.code === 'ERR_AMOUNT_MUST_BE_NUMBER') {
  23. console.error('wrong type')
  24. } else if (err.code === 'ERRO_AMOUNT_MUST_EXCEED_ZERO') {
  25. console.error('out of range')
  26. } else if (err.code === 'ERR_MUST_BE_EVEN') {
  27. console.error('cannot be odd')
  28. } else {
  29. console.error('Unknown error', err)
  30. }
  31. }

"Rejections" subsection

The doTask function does not "codify" TypeError and RangeError.

  1. function doTask (amount) {
  2. return new Promise((resolve, reject) => {
  3. if (typeof amount !== 'number') {
  4. reject(new TypeError('amount must be a number'))
  5. return
  6. }
  7. if (amount <= 0) {
  8. reject(new RangeError('amount must be greater than zero'))
  9. return
  10. }
  11. if (amount % 2) {
  12. reject(new OddError('amount'))
  13. return
  14. }
  15. resolve(amount/2)
  16. })
  17. }
  18.  
  19.  
  20. doTask(3)
  21. .then((result) => {
  22. console.log('result', result)
  23. })
  24. .catch((err) => {
  25. if (err.code === 'ERR_AMOUNT_MUST_BE_NUMBER') {
  26. console.error('wrong type')
  27. } else if (err.code === 'ERRO_AMOUNT_MUST_EXCEED_ZERO') {
  28. console.error('out of range')
  29. } else if (err.code === 'ERR_MUST_BE_EVEN') {
  30. console.error('cannot be odd')
  31. } else {
  32. console.error('Unknown error', err)
  33. }
  34.  
  35. })

Comments

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Welcome!

It looks like you're new here. Sign in or register to get started.
Sign In

Categories

Upcoming Training