0

I'm currently working on some tests scripts for my project. The code is written in ES7 and compiled using babel


First some background:

Let's say you run npm test and the test file looks like this:

function foo (bar) {
  if (!bar) throw new Error('foooo')
  console.log(bar)
}
foo() // No argument given

Now when you run this script the npm will show you an error like this:

$ npm ERR! Test failed.  See above for more details.

This is the desired output, something went wrong, you do not want to release this software yet since there's an error in there.

So what's my question?


Okey so I have a test script setup like this:

async function init () {
  const status = await someRequestPromise()
  if (status.error) throw status.error
  console.log(status.result) // Log the result of this async request...
}
init()

To run my test first I compile the ES7 using babel like so:

$ babel src -d dist

and then run npm test


The result

CLI screenshot To be clear, npm did not trigger the error...

I also tried the following code, however this did not change anything...

async function init () {
  const status = await someRequestPromise()
  if (status.error) throw status.error
  console.log(status.result) // Log the result of this async request...
} 

try {
  init()
} catch (e) {
  console.log(e)
}

I'd like to know how I can trigger npm to catch the error and report the fact that the test failed. Also I'd like to know how to catch the error's, since node marks them as unhandled right now, even with the try catch block.

PS. adding an await statement in front of the init() function causes a syntax error, please don't suggest that.

4

2 Answers 2

0

since async/await returns promises, you must handle rejections (just as the console output suggests) via .catch:

const handle = init()
handle
  .then((result) => handleSuccess(result))
  .catch(({message}) => console.log(message))

try/catch (at least, in my experience)is for sync code.

EDIT:

To make the script 'crash', You may just add a process.exit(1).

const handle = init()
handle
  .then((result) => handleSuccess(result))
  .catch(({message}) => {
     console.log(message)
     process.exit(1)
   })
Sign up to request clarification or add additional context in comments.

5 Comments

I'll look into it. Though try/catch blocks where best practice in combo with async/await
Yes it is, if you're handling errors within the async function and not outside -- just like its predecessor, ES6 Generators. Does that make sense? Also, where'd you find that information about try/catch?
Information was based upon my very own memory haha. Read it somewhere someday... (I'll test the .catch() approach quickly)
Okey so yeah, while that is the desired way to handle any errors its still not a valid way to make npm actually catch the fact that the program failed. You're handeling the error and therefore it's expected... the script won't crash.
simply add process.exit(1) in the catch section
0

Years late, but I believe one correct way to do this (without top level await) is to move the try catch into the 'init' function

async function init () {
  // Try / catch with async / await is basically syntactic sugar for resolve() / reject() 
  try {
    // This async call MUST use await or the promise will not resolve here, 
    // and thus the try / catch wrapping the async call will not trigger
    const status = await someRequestPromise() 
    
    if (status.error) {
      // Throw to reject the promise returned from init()
      throw status.error
    }

    // Log the success of this async request
    console.log(status.result) 
  // Catch your error to do logging.
  } catch (e) {
    // Log the failure of this async request
    console.log(e) 

    // Rethrow to return the promise as rejected (with result as the error object)
    // If you do not rethrow, the promise from init() will return as resolved
    throw e 
  }
  // Return the promise from init() as fulfilled (with result as void)
} 

// Use a thenable to initiate the promise chain at the top level
init().then();

The comments might not be 100% accurate, but it's trying to get the idea across.

Basically a try catch can be used to resolve or reject promises, but only if the promises are awaited somewhere within the try/catch

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.