_errors.js.flow 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // @flow
  2. // based on https://github.com/styled-components/styled-components/blob/fcf6f3804c57a14dd7984dfab7bc06ee2edca044/src/utils/error.js
  3. declare var preval: Function
  4. /**
  5. * Parse errors.md and turn it into a simple hash of code: message
  6. * @private
  7. */
  8. const ERRORS = preval`
  9. const fs = require('fs');
  10. const md = fs.readFileSync(__dirname + '/errors.md', 'utf8');
  11. module.exports = md.split(/^#/gm).slice(1).reduce((errors, str) => {
  12. const [, code, message] = str.split(/^.*?(\\d+)\\s*\\n/)
  13. errors[code] = message
  14. return errors;
  15. }, {});
  16. `
  17. /**
  18. * super basic version of sprintf
  19. * @private
  20. */
  21. function format(...args) {
  22. let a = args[0]
  23. const b = []
  24. let c
  25. for (c = 1; c < args.length; c += 1) {
  26. b.push(args[c])
  27. }
  28. b.forEach(d => {
  29. a = a.replace(/%[a-z]/, d)
  30. })
  31. return a
  32. }
  33. /**
  34. * Create an error file out of errors.md for development and a simple web link to the full errors
  35. * in production mode.
  36. * @private
  37. */
  38. export default class PolishedError extends Error {
  39. constructor(code: string | number, ...args: Array<any>) {
  40. if (process.env.NODE_ENV === 'production') {
  41. super(
  42. `An error occurred. See https://github.com/styled-components/polished/blob/main/src/internalHelpers/errors.md#${code} for more information.`,
  43. )
  44. } else {
  45. super(format(ERRORS[code], ...args))
  46. }
  47. }
  48. }