UserError.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. import type { UserErrors, UserFieldError } from '#shared/types/error.ts'
  3. import getUuid from '#shared/utils/getUuid.ts'
  4. export default class UserError extends Error {
  5. public userErrorId: string
  6. public errors: UserErrors
  7. public generalErrors: ReadonlyArray<string>
  8. public fieldErrors: ReadonlyArray<UserFieldError>
  9. constructor(errors: UserErrors, userErrorId?: string) {
  10. super()
  11. this.userErrorId = userErrorId || getUuid()
  12. this.errors = errors
  13. this.generalErrors = errors
  14. .filter((error) => !error.field)
  15. .map((error) => error.message)
  16. this.fieldErrors = errors.filter(
  17. (error) => error.field,
  18. ) as ReadonlyArray<UserFieldError>
  19. // Set the prototype explicitly.
  20. Object.setPrototypeOf(this, new.target.prototype)
  21. }
  22. public getFirstErrorMessage(): string {
  23. return this.errors[0].message
  24. }
  25. public getFieldErrorList(): Record<string, string> {
  26. return this.fieldErrors.reduce(
  27. (fieldErrorList: Record<string, string>, fieldError) => {
  28. fieldErrorList[fieldError.field] = fieldError.message
  29. return fieldErrorList
  30. },
  31. {},
  32. )
  33. }
  34. }