next-form-action
Version:
A TypeScript library for handling server actions in Next.js with type-safe error handling and callbacks
46 lines • 1.53 kB
JavaScript
export class ActionResponse extends Error {
constructor(state) {
super(state.message);
this.state = state;
}
}
export class ActionError extends ActionResponse {
constructor(state) {
super(state);
}
}
export class ActionSuccess extends ActionResponse {
constructor(state) {
super(state);
}
}
function isNextSystemError(error) {
return error instanceof Error && "digest" in error && typeof error.digest === "string" && error.digest.startsWith("NEXT_");
}
export function error(message, params = {}) {
throw new ActionError({ success: false, message, ...params });
}
export function success(message, params = {}) {
throw new ActionSuccess({ success: true, message, ...params });
}
export function createAction(handler, context) {
return async (data) => {
try {
return await handler(data);
}
catch (caughtError) {
if (caughtError instanceof ActionResponse) {
return caughtError.state;
}
if (isNextSystemError(caughtError)) {
throw caughtError;
}
console.error(`Error in action${context ? ` "${context}"` : ""}:`, caughtError);
const message = caughtError instanceof Error && caughtError.message
? caughtError.message
: "An unexpected error occurred. Please try again.";
return new ActionError({ success: false, message }).state;
}
};
}
//# sourceMappingURL=index.js.map