Skip to content

Commit

Permalink
Improve syntax error messages (#480)
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop authored May 8, 2018
1 parent 73b34cc commit 81bbfee
Showing 1 changed file with 28 additions and 4 deletions.
32 changes: 28 additions & 4 deletions lib/tty-error.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ var cwd = process.cwd()
module.exports = ttyError

function ttyError (src, sub, err) {
if (!err.filename || !err.loc) return err
var longFilename = err.filename || err.fileName
if (!longFilename || !getErrorLocation(err)) return err

var longFilename = err.filename
var filename = path.relative(cwd, longFilename)
var loc = err.loc
var loc = getErrorLocation(err)
var line = loc.line
var col = loc.column + 1

var lineNum = String(line) + ' '
var padLen = lineNum.length
var empty = padLeft('|', padLen + 1)
var arrow = padLeft('--> ', padLen + 4 - 1)
var syntaxError = padLeft('', col) + '^ Syntax Error'
var syntaxError = padLeft('', col) + '^ ' + getErrorMessage(err)

try {
var file = fs.readFileSync(longFilename, 'utf8')
Expand Down Expand Up @@ -65,3 +65,27 @@ function pad (len, char) {
while (res.length < len) res += char
return res
}

function getErrorLocation (err) {
if (err.loc) return err.loc
if (typeof err.line === 'number' && typeof err.column === 'number') {
return {
line: err.line,
column: err.column
}
}
return null
}

function getErrorMessage (err) {
var loc = getErrorLocation(err)
var message = err.message
// strip file names
.replace(/^.*?:|while parsing file:.*?$/g, '')
// strip position in file
.replace('(' + loc.line + ':' + loc.column + ')', '')
// same, but for typescript
.replace('(' + loc.line + ',' + loc.column + ')', '')

return message || 'Syntax Error'
}

0 comments on commit 81bbfee

Please sign in to comment.