UserError.ts 1.4 KB

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