errors.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. const generateErrors = (errors, f) => {
  2. // Exact/regex match to create {CODE: ErrorClassName}
  3. const exactMatch = [];
  4. const regexMatch = [];
  5. // Find out what subclasses to import and which to create
  6. const importBase = new Set();
  7. const createBase = {};
  8. for (const error of errors) {
  9. if (error.subclassExists) {
  10. importBase.add(error.subclass);
  11. } else {
  12. createBase[error.subclass] = error.intCode;
  13. }
  14. if (error.hasCaptures) {
  15. regexMatch.push(error);
  16. } else {
  17. exactMatch.push(error);
  18. }
  19. }
  20. // Imports and new subclass creation
  21. f.write(
  22. `const { RPCError, ${[...importBase.values()].join(
  23. ', '
  24. )} } = require('./rpcbaseerrors');`
  25. );
  26. f.write("\nconst format = require('string-format');");
  27. for (const [cls, intCode] of Object.entries(createBase)) {
  28. f.write(
  29. `\n\nclass ${cls} extends RPCError {\n constructor() {\n this.code = ${intCode};\n }\n}`
  30. );
  31. }
  32. // Error classes generation
  33. for (const error of errors) {
  34. f.write(
  35. `\n\nclass ${error.name} extends ${error.subclass} {\n constructor(args) {\n `
  36. );
  37. if (error.hasCaptures) {
  38. f.write(
  39. `const ${error.captureName} = Number(args.capture || 0);\n `
  40. );
  41. }
  42. const capture = error.description.replace(/'/g, "\\'");
  43. if (error.hasCaptures) {
  44. f.write(`super(format('${capture}', {${error.captureName}})`);
  45. } else {
  46. f.write(`super('${capture}'`);
  47. }
  48. f.write(' + RPCError._fmtRequest(args.request));\n');
  49. if (error.hasCaptures) {
  50. f.write(
  51. ` this.${error.captureName} = ${error.captureName};\n`
  52. );
  53. }
  54. f.write(' }\n}\n');
  55. }
  56. f.write('\n\nconst rpcErrorsObject = {\n');
  57. for (const error of exactMatch) {
  58. f.write(` ${error.pattern}: ${error.name},\n`);
  59. }
  60. f.write('};\n\nconst rpcErrorRe = [\n');
  61. for (const error of regexMatch) {
  62. f.write(` [/${error.pattern}/, ${error.name}],\n`);
  63. }
  64. f.write('];');
  65. f.write("module.exports = {");
  66. for (const error of regexMatch) {
  67. f.write(` ${error.name},\n`);
  68. }
  69. for (const error of exactMatch) {
  70. f.write(` ${error.name},\n`);
  71. }
  72. f.write(" rpcErrorsObject,\n");
  73. f.write(" rpcErrorRe,\n");
  74. f.write("}");
  75. };
  76. module.exports = {
  77. generateErrors,
  78. };