parse-pretty-error.js 1.0 KB

123456789101112131415161718192021222324252627282930313233
  1. 'use strict'
  2. module.exports = prettyError
  3. function prettyError (err, buf) {
  4. /* istanbul ignore if */
  5. if (err.pos == null || err.line == null) return err
  6. let msg = err.message
  7. msg += ` at row ${err.line + 1}, col ${err.col + 1}, pos ${err.pos}:\n`
  8. /* istanbul ignore else */
  9. if (buf && buf.split) {
  10. const lines = buf.split(/\n/)
  11. const lineNumWidth = String(Math.min(lines.length, err.line + 3)).length
  12. let linePadding = ' '
  13. while (linePadding.length < lineNumWidth) linePadding += ' '
  14. for (let ii = Math.max(0, err.line - 1); ii < Math.min(lines.length, err.line + 2); ++ii) {
  15. let lineNum = String(ii + 1)
  16. if (lineNum.length < lineNumWidth) lineNum = ' ' + lineNum
  17. if (err.line === ii) {
  18. msg += lineNum + '> ' + lines[ii] + '\n'
  19. msg += linePadding + ' '
  20. for (let hh = 0; hh < err.col; ++hh) {
  21. msg += ' '
  22. }
  23. msg += '^\n'
  24. } else {
  25. msg += lineNum + ': ' + lines[ii] + '\n'
  26. }
  27. }
  28. }
  29. err.message = msg + '\n'
  30. return err
  31. }