UserError.ts 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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 getFirstErrorException(): string | undefined | null {
  26. return this.errors[0].exception
  27. }
  28. public getFieldErrorList(): Record<string, string> {
  29. return this.fieldErrors.reduce(
  30. (fieldErrorList: Record<string, string>, fieldError) => {
  31. fieldErrorList[fieldError.field] = fieldError.message
  32. return fieldErrorList
  33. },
  34. {},
  35. )
  36. }
  37. }