Use try/catch to handle errors

Actions might fail silently if you don't explicitly handle errors. To ensure your hooks are robust and maintainable, always wrap actions in try/catch blocks.

You can use try/catch to:

  • Catch and log errors for debugging
  • Implement fallback behavior when actions fail
  • Prevent your hook from crashing unexpectedly

This example tries to download from a non-existent website:

module.exports = async function (payload, actions) {
  try {
    const { data } = await actions.http.get('https://no-such-website.dev');
  } catch (err) {
    console.error('Error occured: ', err)
  }
}

Here is the result of the test run:

Best practices:

  • Always include try/catch blocks around actions that might fail
  • Use descriptive error messages that help identify the failure point
  • Consider whether to throw errors or handle them gracefully
  • Log errors appropriately using console.error()

❌ Incorrect usage:

module.exports = async function (payload, actions) {
	// No error handling!
	const { data } = await actions.http.get('https://no-such-website.dev');
	console.log('Downloaded page: ', data)
}