custom.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. var prr = require('prr')
  2. function init (type, message, cause) {
  3. if (!!message && typeof message != 'string') {
  4. message = message.message || message.name
  5. }
  6. prr(this, {
  7. type : type
  8. , name : type
  9. // can be passed just a 'cause'
  10. , cause : typeof message != 'string' ? message : cause
  11. , message : message
  12. }, 'ewr')
  13. }
  14. // generic prototype, not intended to be actually used - helpful for `instanceof`
  15. function CustomError (message, cause) {
  16. Error.call(this)
  17. if (Error.captureStackTrace)
  18. Error.captureStackTrace(this, this.constructor)
  19. init.call(this, 'CustomError', message, cause)
  20. }
  21. CustomError.prototype = new Error()
  22. function createError (errno, type, proto) {
  23. var err = function (message, cause) {
  24. init.call(this, type, message, cause)
  25. //TODO: the specificity here is stupid, errno should be available everywhere
  26. if (type == 'FilesystemError') {
  27. this.code = this.cause.code
  28. this.path = this.cause.path
  29. this.errno = this.cause.errno
  30. this.message =
  31. (errno.errno[this.cause.errno]
  32. ? errno.errno[this.cause.errno].description
  33. : this.cause.message)
  34. + (this.cause.path ? ' [' + this.cause.path + ']' : '')
  35. }
  36. Error.call(this)
  37. if (Error.captureStackTrace)
  38. Error.captureStackTrace(this, err)
  39. }
  40. err.prototype = !!proto ? new proto() : new CustomError()
  41. return err
  42. }
  43. module.exports = function (errno) {
  44. var ce = function (type, proto) {
  45. return createError(errno, type, proto)
  46. }
  47. return {
  48. CustomError : CustomError
  49. , FilesystemError : ce('FilesystemError')
  50. , createError : ce
  51. }
  52. }