From 93b78eabd321bab7e4191a65e252ad62366b45dd Mon Sep 17 00:00:00 2001 From: Grische Date: Fri, 26 Jul 2024 13:08:00 +0200 Subject: [PATCH] improve error handling when calling json-to-go.js --- .github/workflows/node-tests.yml | 10 ++++++++++ json-to-go.js | 15 ++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.github/workflows/node-tests.yml b/.github/workflows/node-tests.yml index 550b338..2bdd7dc 100644 --- a/.github/workflows/node-tests.yml +++ b/.github/workflows/node-tests.yml @@ -54,3 +54,13 @@ jobs: exp=$(cat tests/double-nested-objects.go) echo "got: '${got}'" [[ "${got}" == "${exp}" ]] + + - name: Check correct error handling using stdin + shell: bash + run: | + ! node json-to-go.js <<< "error" + + - name: Check correct error handling with a file + shell: bash + run: | + ! node json-to-go.js <(echo "error") diff --git a/json-to-go.js b/json-to-go.js index 15f4b9b..fb31523 100644 --- a/json-to-go.js +++ b/json-to-go.js @@ -498,6 +498,15 @@ if (typeof module != 'undefined') { let bigstdin = false let filename = null + function jsonToGoWithErrorHandling(json) { + const output = jsonToGo(json) + if (output.error) { + console.error(output.error) + process.exitCode = 1 + } + process.stdout.write(output.go) + } + process.argv.forEach((val, index) => { if (index < 2) return @@ -519,7 +528,7 @@ if (typeof module != 'undefined') { if (filename) { const fs = require('fs'); const json = fs.readFileSync(filename, 'utf8'); - process.stdout.write(jsonToGo(json).go) + jsonToGoWithErrorHandling(json) return } @@ -530,7 +539,7 @@ if (typeof module != 'undefined') { }) process.stdin.on('end', function() { const json = Buffer.concat(bufs).toString('utf8') - process.stdout.write(jsonToGo(json).go) + jsonToGoWithErrorHandling(json) }) return } @@ -538,7 +547,7 @@ if (typeof module != 'undefined') { // read from stdin process.stdin.on('data', function(buf) { const json = buf.toString('utf8') - process.stdout.write(jsonToGo(json).go) + jsonToGoWithErrorHandling(json) }) } else { module.exports = jsonToGo