From a9d1106e5da067e57caed9a56f07ad0af6d89298 Mon Sep 17 00:00:00 2001
From: Lawson Kurtz <lawson.kurtz@viget.com>
Date: Wed, 27 Jul 2016 17:07:52 -0600
Subject: [PATCH] Improve error handling within e2e.sh (#244)

* Improve error handling in E2E script

* Expose e2e.sh as npm test script
---
 package.json |  3 ++-
 tasks/e2e.sh | 30 ++++++++++++++++++++++++------
 2 files changed, 26 insertions(+), 7 deletions(-)

diff --git a/package.json b/package.json
index 9ab14126f5a..d75c3fc67f6 100644
--- a/package.json
+++ b/package.json
@@ -13,7 +13,8 @@
   "scripts": {
     "start": "node scripts/start.js --debug-template",
     "build": "node scripts/build.js --debug-template",
-    "create-react-app": "node global-cli/index.js --scripts-version \"$PWD/`npm pack`\""
+    "create-react-app": "node global-cli/index.js --scripts-version \"$PWD/`npm pack`\"",
+    "test": "tasks/e2e.sh"
   },
   "files": [
     "LICENSE",
diff --git a/tasks/e2e.sh b/tasks/e2e.sh
index 85edc4b08a4..8a4a1ffa364 100755
--- a/tasks/e2e.sh
+++ b/tasks/e2e.sh
@@ -8,10 +8,29 @@
 # Start in tests/ even if run from root directory
 cd "$(dirname "$0")"
 
-# Exit the script on any command with non 0 return code
-# We assume that all the commands in the pipeline set their return code
-# properly and that we do not need to validate that the output is correct
-set -e
+function cleanup {
+  echo 'Cleaning up.'
+  cd $initial_path
+  rm -rf $temp_cli_path $temp_app_path
+}
+
+function handle_error {
+  echo "$(basename $0): \033[31mERROR!\033[m An error was encountered executing \033[36mline $1\033[m."
+  handle_exit
+  exit 1
+}
+
+function handle_exit {
+  cleanup
+  echo 'Exiting.'
+  exit
+}
+
+# Exit the script with a helpful error message when any error is encountered
+trap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR
+
+# Cleanup before exit on any termination signal
+trap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP
 
 # Echo every command being executed
 set -x
@@ -81,5 +100,4 @@ test -e build/*.js
 npm start -- --smoke-test
 
 # Cleanup
-cd $initial_path
-rm -rf $temp_cli_path $temp_app_path
+cleanup