errors.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. class YAMLError extends Error {
  3. constructor(name, pos, code, message) {
  4. super();
  5. this.name = name;
  6. this.code = code;
  7. this.message = message;
  8. this.pos = pos;
  9. }
  10. }
  11. class YAMLParseError extends YAMLError {
  12. constructor(pos, code, message) {
  13. super('YAMLParseError', pos, code, message);
  14. }
  15. }
  16. class YAMLWarning extends YAMLError {
  17. constructor(pos, code, message) {
  18. super('YAMLWarning', pos, code, message);
  19. }
  20. }
  21. const prettifyError = (src, lc) => (error) => {
  22. if (error.pos[0] === -1)
  23. return;
  24. error.linePos = error.pos.map(pos => lc.linePos(pos));
  25. const { line, col } = error.linePos[0];
  26. error.message += ` at line ${line}, column ${col}`;
  27. let ci = col - 1;
  28. let lineStr = src
  29. .substring(lc.lineStarts[line - 1], lc.lineStarts[line])
  30. .replace(/[\n\r]+$/, '');
  31. // Trim to max 80 chars, keeping col position near the middle
  32. if (ci >= 60 && lineStr.length > 80) {
  33. const trimStart = Math.min(ci - 39, lineStr.length - 79);
  34. lineStr = '…' + lineStr.substring(trimStart);
  35. ci -= trimStart - 1;
  36. }
  37. if (lineStr.length > 80)
  38. lineStr = lineStr.substring(0, 79) + '…';
  39. // Include previous line in context if pointing at line start
  40. if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
  41. // Regexp won't match if start is trimmed
  42. let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
  43. if (prev.length > 80)
  44. prev = prev.substring(0, 79) + '…\n';
  45. lineStr = prev + lineStr;
  46. }
  47. if (/[^ ]/.test(lineStr)) {
  48. let count = 1;
  49. const end = error.linePos[1];
  50. if (end && end.line === line && end.col > col) {
  51. count = Math.max(1, Math.min(end.col - col, 80 - ci));
  52. }
  53. const pointer = ' '.repeat(ci) + '^'.repeat(count);
  54. error.message += `:\n\n${lineStr}\n${pointer}\n`;
  55. }
  56. };
  57. exports.YAMLError = YAMLError;
  58. exports.YAMLParseError = YAMLParseError;
  59. exports.YAMLWarning = YAMLWarning;
  60. exports.prettifyError = prettifyError;