Skip to content

Commit

Permalink
fix error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
e-moran committed Jan 10, 2025
1 parent a6dcec4 commit af75332
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 5 deletions.
13 changes: 11 additions & 2 deletions examples/nextjs-bot-categories/app/api/arcjet/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,21 @@ function checkSpoofed(rule: ArcjetRuleResult) {
return rule.reason.isBot() && rule.reason.isSpoofed()
}

function collectErrors(errors: string[], rule: ArcjetRuleResult) {
if (rule.reason.isError()) {
return [...errors, rule.reason.message];
} else {
return errors;
}
}

export async function GET(req: Request) {
const decision = await aj.protect(req);

if (decision.isErrored()) {
const errors = decision.results.reduce(collectErrors, []);
if (errors.length > 0) {
return NextResponse.json(
{ error: decision.reason.message },
{ errors },
{ status: 500, statusText: "Internal Server Error" },
)
}
Expand Down
15 changes: 12 additions & 3 deletions examples/nextjs-server-actions/app/actions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"use server"

import arcjet, { request, validateEmail } from "@arcjet/next";
import arcjet, { ArcjetRuleResult, request, validateEmail } from "@arcjet/next";

const aj = arcjet({
key: process.env.ARCJET_KEY!,
Expand All @@ -11,6 +11,14 @@ const aj = arcjet({
]
});

function collectErrors(errors: string[], rule: ArcjetRuleResult) {
if (rule.reason.isError()) {
return [...errors, rule.reason.message];
} else {
return errors;
}
}

export async function validate(prev: { message: string }, formData: FormData) {
const email = formData.get("email");

Expand All @@ -28,8 +36,9 @@ export async function validate(prev: { message: string }, formData: FormData) {

// If Arcjet encounters an error, you could fail "open" or you could respond
// with a "closed"-style message like below
if (decision.isErrored()) {
console.log("Error occurred:", decision.reason.message);
const errors = decision.results.reduce(collectErrors, []);
if (errors.length > 0) {
console.log("Errors occurred:", errors);
return {
message: "Encountered an error"
}
Expand Down

0 comments on commit af75332

Please sign in to comment.