errors.js 2.0 KB

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