Skip to content

Commit 93b78ea

Browse files
committed
improve error handling when calling json-to-go.js
1 parent b490b8c commit 93b78ea

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

.github/workflows/node-tests.yml

+10
Original file line numberDiff line numberDiff line change
@@ -54,3 +54,13 @@ jobs:
5454
exp=$(cat tests/double-nested-objects.go)
5555
echo "got: '${got}'"
5656
[[ "${got}" == "${exp}" ]]
57+
58+
- name: Check correct error handling using stdin
59+
shell: bash
60+
run: |
61+
! node json-to-go.js <<< "error"
62+
63+
- name: Check correct error handling with a file
64+
shell: bash
65+
run: |
66+
! node json-to-go.js <(echo "error")

json-to-go.js

+12-3
Original file line numberDiff line numberDiff line change
@@ -498,6 +498,15 @@ if (typeof module != 'undefined') {
498498
let bigstdin = false
499499
let filename = null
500500

501+
function jsonToGoWithErrorHandling(json) {
502+
const output = jsonToGo(json)
503+
if (output.error) {
504+
console.error(output.error)
505+
process.exitCode = 1
506+
}
507+
process.stdout.write(output.go)
508+
}
509+
501510
process.argv.forEach((val, index) => {
502511
if (index < 2)
503512
return
@@ -519,7 +528,7 @@ if (typeof module != 'undefined') {
519528
if (filename) {
520529
const fs = require('fs');
521530
const json = fs.readFileSync(filename, 'utf8');
522-
process.stdout.write(jsonToGo(json).go)
531+
jsonToGoWithErrorHandling(json)
523532
return
524533
}
525534

@@ -530,15 +539,15 @@ if (typeof module != 'undefined') {
530539
})
531540
process.stdin.on('end', function() {
532541
const json = Buffer.concat(bufs).toString('utf8')
533-
process.stdout.write(jsonToGo(json).go)
542+
jsonToGoWithErrorHandling(json)
534543
})
535544
return
536545
}
537546

538547
// read from stdin
539548
process.stdin.on('data', function(buf) {
540549
const json = buf.toString('utf8')
541-
process.stdout.write(jsonToGo(json).go)
550+
jsonToGoWithErrorHandling(json)
542551
})
543552
} else {
544553
module.exports = jsonToGo

0 commit comments

Comments
 (0)