I want to ensure that a page can only be created from the default locale, as I need to ensure it's default pathname is created, before any sort of localized pathname is added.
I'd like to do something like this:
if (operation === "create" && isDefaultLocale) {
throw new Error("Pages must be created within the default locale.");
}
However, that error only shows in the server's console. Is there a way I can send that error message to the client, in order to be displayed within a toast message/notification, instead of saying a non-descriptive "Something went wrong"?
In order for an error to show up in the toast notification it must have the
isPublic
property on it.
The easiest way to do this would be to extend our existing
APIError
with a new class, then throw that class. Here is an example:
import { APIError } from 'payload/errors'
class MySpecialError extends APIError {
constructor(message: string) {
super(message, 400, undefined, true)
}
}
The 4th parameter is the
isPublic
value.
Then throw as you'd expect
throw new MySpecialError('Cannot create in default locale')
Thank you 👍🏻
When I try to do this i get this error:
TypeError: Class constructor APIError cannot be invoked without 'new'
Seems to be related to this:
Any ideas? thanks
Can you show your code?
@denolfe
errorClasses.ts
import { APIError } from "payload/errors";
export class CustomAdminError extends APIError {
constructor(message: string, statusCode: number) {
super(message, statusCode, undefined, true)
}
}
export default CustomAdminError;
Calling it from a hook here:
export const blockSuperAdminCreation: CollectionBeforeValidateHook = async ({
data,
req,
operation,
originalDoc
}) => {
if (operation === "create") {
// If user is trying to create a super_admin, make sure they themselves are a super_admin
if (data.roles.includes("super_admin")) {
if (req.user.roles.includes("super_admin")) {
return data
}
else {
//TODO: throw toast error
throw new CustomAdminError(`You are not allowed to access this site, please proceed to your site's domain`, 403)
}
} else {
// If not creating super_admin, pass to creation accesss control
return data
}
}
}
i do get the same error, would be awesome if someone could help us!
my error call does exist inside a beforeChange hook:
throw new ConflictsError(
Konflikte bei ContentIdentifierIDs gefunden: ${JSON.stringify(conflicts)}
);
import { APIError } from 'payload/errors'
class ConflictsError extends APIError {
constructor(message: string) {
super(message, 400, undefined, true)
}
}
[14:52:26] ERROR (payload): TypeError: Class constructor APIError cannot be invoked without 'new'
at new ConflictsError
@denolfe
Likely something to do w/ your tsconfig.json target.
Try using
ES2017
or greater
That solved my problem. Thank you!
Star
Discord
online
Get help straight from the Payload team with an Enterprise License.