logo

pleroma-fe

My custom branche(s) on git.pleroma.social/pleroma/pleroma-fe git clone https://anongit.hacktivis.me/git/pleroma-fe.git/

errors.js (2123B)


  1. import { capitalize } from 'lodash'
  2. function humanizeErrors (errors) {
  3. return Object.entries(errors).reduce((errs, [k, val]) => {
  4. const message = val.reduce((acc, message) => {
  5. const key = capitalize(k.replace(/_/g, ' '))
  6. return acc + [key, message].join(' ') + '. '
  7. }, '')
  8. return [...errs, message]
  9. }, [])
  10. }
  11. export function StatusCodeError (statusCode, body, options, response) {
  12. this.name = 'StatusCodeError'
  13. this.statusCode = statusCode
  14. this.message = statusCode + ' - ' + (JSON && JSON.stringify ? JSON.stringify(body) : body)
  15. this.error = body // legacy attribute
  16. this.options = options
  17. this.response = response
  18. if (Error.captureStackTrace) { // required for non-V8 environments
  19. Error.captureStackTrace(this)
  20. }
  21. }
  22. StatusCodeError.prototype = Object.create(Error.prototype)
  23. StatusCodeError.prototype.constructor = StatusCodeError
  24. export class RegistrationError extends Error {
  25. constructor (error) {
  26. super()
  27. if (Error.captureStackTrace) {
  28. Error.captureStackTrace(this)
  29. }
  30. try {
  31. // the error is probably a JSON object with a single key, "errors", whose value is another JSON object containing the real errors
  32. if (typeof error === 'string') {
  33. error = JSON.parse(error)
  34. // eslint-disable-next-line
  35. if (error.hasOwnProperty('error')) {
  36. error = JSON.parse(error.error)
  37. }
  38. }
  39. if (typeof error === 'object') {
  40. const errorContents = JSON.parse(error.error)
  41. // keys will have the property that has the error, for example 'ap_id',
  42. // 'email' or 'captcha', the value will be an array of its error
  43. // like "ap_id": ["has been taken"] or "captcha": ["Invalid CAPTCHA"]
  44. // replace ap_id with username
  45. if (errorContents.ap_id) {
  46. errorContents.username = errorContents.ap_id
  47. delete errorContents.ap_id
  48. }
  49. this.message = humanizeErrors(errorContents)
  50. } else {
  51. this.message = error
  52. }
  53. } catch {
  54. // can't parse it, so just treat it like a string
  55. this.message = error
  56. }
  57. }
  58. }