index.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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.slice(start, end).map(function(text, i){
  16. var curr = i + start + 1;
  17. var preamble = (curr == line ? ' > ' : ' ')
  18. + curr
  19. + '| ';
  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. }).join('\n');
  27. fullMessage = (filename || 'Pug') + ':' + location + '\n' + context + '\n\n' + message;
  28. } else {
  29. fullMessage = (filename || 'Pug') + ':' + location + '\n\n' + message;
  30. }
  31. var err = new Error(fullMessage);
  32. err.code = 'PUG:' + code;
  33. err.msg = message;
  34. err.line = line;
  35. err.column = column;
  36. err.filename = filename;
  37. err.src = src;
  38. err.toJSON = function () {
  39. return {
  40. code: this.code,
  41. msg: this.msg,
  42. line: this.line,
  43. column: this.column,
  44. filename: this.filename
  45. };
  46. };
  47. return err;
  48. }