errors.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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(`const { RPCError, ${[...importBase.values()].join(', ')} } = require('./rpcbaseerrors');`)
  22. f.write('\nconst format = require(\'string-format\');')
  23. for (const [cls, intCode] of Object.entries(createBase)) {
  24. f.write(`\n\nclass ${cls} extends RPCError {\n constructor() {\n this.code = ${intCode};\n }\n}`)
  25. }
  26. // Error classes generation
  27. for (const error of errors) {
  28. f.write(`\n\nclass ${error.name} extends ${error.subclass} {\n constructor(args) {\n `)
  29. if (error.hasCaptures) {
  30. f.write(`const ${error.captureName} = Number(args.capture || 0);\n `)
  31. }
  32. const capture = error.description.replace(/'/g, '\\\'')
  33. if (error.hasCaptures) {
  34. f.write(`super(format('${capture}', {${error.captureName}})`)
  35. } else {
  36. f.write(`super('${capture}'`)
  37. }
  38. f.write(' + RPCError._fmtRequest(args.request));\n')
  39. if (error.hasCaptures) {
  40. f.write(` this.${error.captureName} = ${error.captureName};\n`)
  41. }
  42. f.write(' }\n}\n')
  43. }
  44. f.write('\n\nconst rpcErrorsObject = {\n')
  45. for (const error of exactMatch) {
  46. f.write(` ${error.pattern}: ${error.name},\n`)
  47. }
  48. f.write('};\n\nconst rpcErrorRe = [\n')
  49. for (const error of regexMatch) {
  50. f.write(` [/${error.pattern}/, ${error.name}],\n`)
  51. }
  52. f.write('];')
  53. f.write('module.exports = {')
  54. for (const error of regexMatch) {
  55. f.write(` ${error.name},\n`)
  56. }
  57. for (const error of exactMatch) {
  58. f.write(` ${error.name},\n`)
  59. }
  60. f.write(' rpcErrorsObject,\n')
  61. f.write(' rpcErrorRe,\n')
  62. f.write('}')
  63. }
  64. module.exports = {
  65. generateErrors,
  66. }