Skip to content

Commit

Permalink
improve error handling when calling json-to-go.js
Browse files Browse the repository at this point in the history
  • Loading branch information
grische committed Jul 26, 2024
1 parent b490b8c commit 93b78ea
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 10 additions & 0 deletions .github/workflows/node-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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")
15 changes: 12 additions & 3 deletions json-to-go.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}

Expand All @@ -530,15 +539,15 @@ 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
}

// 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
Expand Down

0 comments on commit 93b78ea

Please sign in to comment.