index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. 'use strict';
  2. module.exports = makeError;
  3. function makeError(code, message, options) {
  4. var line = options.line;
  5. var column = options.column;
  6. var filename = options.filename;
  7. var src = options.src;
  8. var fullMessage;
  9. var location = line + (column ? ':' + column : '');
  10. if (src && line >= 1 && line <= src.split('\n').length) {
  11. var lines = src.split('\n');
  12. var start = Math.max(line - 3, 0);
  13. var end = Math.min(lines.length, line + 3);
  14. // Error context
  15. var context = lines
  16. .slice(start, end)
  17. .map(function(text, i) {
  18. var curr = i + start + 1;
  19. var preamble = (curr == line ? ' > ' : ' ') + curr + '| ';
  20. var out = preamble + text;
  21. if (curr === line && column > 0) {
  22. out += '\n';
  23. out += Array(preamble.length + column).join('-') + '^';
  24. }
  25. return out;
  26. })
  27. .join('\n');
  28. fullMessage =
  29. (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message;
  30. } else {
  31. fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message;
  32. }
  33. var err = new Error(fullMessage);
  34. err.code = 'PUG:' + code;
  35. err.msg = message;
  36. err.line = line;
  37. err.column = column;
  38. err.filename = filename;
  39. err.src = src;
  40. err.toJSON = function() {
  41. return {
  42. code: this.code,
  43. msg: this.msg,
  44. line: this.line,
  45. column: this.column,
  46. filename: this.filename,
  47. };
  48. };
  49. return err;
  50. }