2026-01-02 13:41:09 +00:00
|
|
|
// Copyright (C) 2012-2026 Zammad Foundation, https://zammad-foundation.org/
|
2022-04-07 07:07:20 +00:00
|
|
|
|
2024-09-17 15:35:54 +00:00
|
|
|
import type { EnumUserErrorException } from '#shared/graphql/types.ts'
|
2025-04-22 15:47:29 +00:00
|
|
|
import { i18n } from '#shared/i18n.ts'
|
2023-04-24 12:50:55 +00:00
|
|
|
import type { UserErrors, UserFieldError } from '#shared/types/error.ts'
|
2024-08-16 10:30:32 +00:00
|
|
|
import getUuid from '#shared/utils/getUuid.ts'
|
2022-04-07 07:07:20 +00:00
|
|
|
|
|
|
|
|
export default class UserError extends Error {
|
2024-08-16 10:30:32 +00:00
|
|
|
public userErrorId: string
|
|
|
|
|
|
2022-04-07 07:07:20 +00:00
|
|
|
public errors: UserErrors
|
|
|
|
|
|
|
|
|
|
public generalErrors: ReadonlyArray<string>
|
|
|
|
|
|
|
|
|
|
public fieldErrors: ReadonlyArray<UserFieldError>
|
|
|
|
|
|
2024-08-16 10:30:32 +00:00
|
|
|
constructor(errors: UserErrors, userErrorId?: string) {
|
2022-04-07 07:07:20 +00:00
|
|
|
super()
|
|
|
|
|
|
2024-08-16 10:30:32 +00:00
|
|
|
this.userErrorId = userErrorId || getUuid()
|
2022-04-07 07:07:20 +00:00
|
|
|
this.errors = errors
|
2025-06-11 17:45:28 +00:00
|
|
|
this.generalErrors = errors.filter((error) => !error.field).map((error) => error.message)
|
|
|
|
|
this.fieldErrors = errors.filter((error) => error.field) as ReadonlyArray<UserFieldError>
|
2022-04-07 07:07:20 +00:00
|
|
|
|
|
|
|
|
// Set the prototype explicitly.
|
|
|
|
|
Object.setPrototypeOf(this, new.target.prototype)
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-16 10:30:32 +00:00
|
|
|
public getFirstErrorMessage(): string {
|
|
|
|
|
return this.errors[0].message
|
|
|
|
|
}
|
|
|
|
|
|
2024-09-17 15:35:54 +00:00
|
|
|
public getFirstErrorException(): EnumUserErrorException | undefined | null {
|
2024-09-06 11:19:57 +00:00
|
|
|
return this.errors[0].exception
|
|
|
|
|
}
|
|
|
|
|
|
2022-04-07 07:07:20 +00:00
|
|
|
public getFieldErrorList(): Record<string, string> {
|
2025-06-11 17:45:28 +00:00
|
|
|
return this.fieldErrors.reduce((fieldErrorList: Record<string, string>, fieldError) => {
|
|
|
|
|
// In case of an array with placeholders, translate the message right here.
|
|
|
|
|
if (fieldError.messagePlaceholder)
|
|
|
|
|
fieldErrorList[fieldError.field] = i18n.t(
|
|
|
|
|
fieldError.message,
|
|
|
|
|
...fieldError.messagePlaceholder,
|
|
|
|
|
)
|
|
|
|
|
// Otherwise, just pass the source string for later translation.
|
|
|
|
|
else fieldErrorList[fieldError.field] = fieldError.message
|
|
|
|
|
|
|
|
|
|
return fieldErrorList
|
|
|
|
|
}, {})
|
2022-04-07 07:07:20 +00:00
|
|
|
}
|
|
|
|
|
}
|