Skip to content

Commit 2e6aaf9

Browse files
committed
feat: implement throwValidationErrors and throwServerError at the action level
1 parent b9858b8 commit 2e6aaf9

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

packages/next-safe-action/src/action-builder.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -291,18 +291,29 @@ export function actionBuilder<
291291
const actionResult: SafeActionResult<ServerError, S, BAS, CVE, CBAVE, Data> = {};
292292

293293
if (typeof middlewareResult.validationErrors !== "undefined") {
294-
if (args.throwValidationErrors) {
294+
// Throw validation errors if either `throwValidationErrors` property at the action or instance level is `true`.
295+
// If `throwValidationErrors` property at the action is `false`, do not throw validation errors, since it
296+
// has a higher priority than the instance one.
297+
if (
298+
(utils?.throwValidationErrors || args.throwValidationErrors) &&
299+
utils?.throwValidationErrors !== false
300+
) {
295301
throw new ActionValidationError(middlewareResult.validationErrors as CVE);
302+
} else {
303+
actionResult.validationErrors = middlewareResult.validationErrors as CVE;
296304
}
297-
actionResult.validationErrors = middlewareResult.validationErrors as CVE;
298305
}
299306

300307
if (typeof middlewareResult.bindArgsValidationErrors !== "undefined") {
301308
actionResult.bindArgsValidationErrors = middlewareResult.bindArgsValidationErrors as CBAVE;
302309
}
303310

304311
if (typeof middlewareResult.serverError !== "undefined") {
305-
actionResult.serverError = middlewareResult.serverError;
312+
if (utils?.throwServerError) {
313+
throw middlewareResult.serverError;
314+
} else {
315+
actionResult.serverError = middlewareResult.serverError;
316+
}
306317
}
307318

308319
if (middlewareResult.success) {

packages/next-safe-action/src/index.types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,8 @@ export type SafeActionUtils<
157157
CBAVE,
158158
Data,
159159
> = {
160+
throwServerError?: boolean;
161+
throwValidationErrors?: boolean;
160162
onSuccess?: (args: {
161163
data?: Data;
162164
metadata: MD;

0 commit comments

Comments
 (0)