Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add formatError property to Blitz server- & rpchandler setup #4124

Merged
merged 13 commits into from
May 1, 2023
Merged
7 changes: 7 additions & 0 deletions .changeset/chatty-gifts-whisper.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@blitzjs/next": minor
"@blitzjs/rpc": minor
"toolkit-app": patch
dbrxnds marked this conversation as resolved.
Show resolved Hide resolved
---

Add ability to format the error on the server before returning it to the client.
1 change: 0 additions & 1 deletion apps/toolkit-app/src/auth/mutations/signup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import db from "db"
import { SecurePassword } from "@blitzjs/auth/secure-password"
import { Role } from "types"

export default async function signup(input, ctx) {
Expand Down
8 changes: 5 additions & 3 deletions apps/toolkit-app/src/blitz-server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import type { BlitzCliConfig } from "blitz"
import { BlitzLogger } from "blitz"
import { setupBlitzServer } from "@blitzjs/next"
import { AuthServerPlugin, PrismaStorage } from "@blitzjs/auth"
import { AuthServerPlugin, PrismaStorage, simpleRolesIsAuthorized } from "@blitzjs/auth"
import db from "db"
import { simpleRolesIsAuthorized } from "@blitzjs/auth"
import { BlitzLogger } from "blitz"

export const cliConfig: BlitzCliConfig = {
customTemplates: "src/templates",
Expand All @@ -27,6 +26,9 @@ const { gSSP, gSP, api } = setupBlitzServer({
isAuthorized: simpleRolesIsAuthorized,
}),
],
formatError: (error) => {
return new Error("Formatted error" + error.message)
},
logger: BlitzLogger({}),
})

Expand Down
9 changes: 8 additions & 1 deletion apps/toolkit-app/src/pages/api/rpc/[[...blitz]].ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { rpcHandler } from "@blitzjs/rpc"
import { api } from "src/blitz-server"

export default api(rpcHandler({ onError: console.log }))
export default api(
rpcHandler({
onError: console.log,
formatError: (error) => {
return new Error("RPC Handler formatted error: " + error.message)
},
})
)
2 changes: 1 addition & 1 deletion apps/toolkit-app/src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const UserInfo = () => {
<Link href={Routes.LoginPage()} className={styles.loginButton}>
<strong>Login</strong>
</Link>
<Link href="/api/auth/github/login" passHref>
<Link href="/api/auth/github/login" passHref legacyBehavior>
<a className="button small">
<strong>Sign in with GitHub</strong>
</a>
Expand Down
1 change: 1 addition & 0 deletions integration-tests/next-13-app-dir/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
3 changes: 2 additions & 1 deletion integration-tests/next-13-app-dir/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
{
"name": "next"
}
]
],
"strictNullChecks": true
},
"exclude": ["node_modules"],
"baseUrl": "."
Expand Down
43 changes: 24 additions & 19 deletions packages/blitz-next/src/index-server.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,43 @@
import type {
NextConfig,
GetServerSideProps,
GetServerSidePropsResult,
GetStaticProps,
GetStaticPropsResult,
NextApiRequest,
NextApiResponse,
NextConfig,
} from "next"
import {
AddParameters,
AsyncFunc,
BlitzLogger,
BlitzServerPlugin,
Ctx as BlitzCtx,
FirstParam,
RequestMiddleware,
MiddlewareResponse,
BlitzLogger,
handleRequestWithMiddleware,
initializeLogger,
Simplify,
UnionToIntersection,
isRouteUrlObject,
MiddlewareResponse,
reduceBlitzServerPlugins,
RouteUrlObject,
startWatcher,
stopWatcher,
} from "blitz"
import {handleRequestWithMiddleware, startWatcher, stopWatcher} from "blitz"
import {installWebpackConfig, InstallWebpackConfigOptions, ResolverPathOptions} from "@blitzjs/rpc"
import {
DefaultOptions,
QueryClient,
getQueryKey,
getInfiniteQueryKey,
dehydrate,
getInfiniteQueryKey,
getQueryKey,
installWebpackConfig,
InstallWebpackConfigOptions,
QueryClient,
ResolverPathOptions,
} from "@blitzjs/rpc"
import {IncomingMessage, ServerResponse} from "http"
import {withSuperJsonProps} from "./superjson"
import {ParsedUrlQuery} from "querystring"
import {PreviewData} from "next/types"
import {resolveHref} from "next/dist/shared/lib/router/utils/resolve-href"
import {RouteUrlObject, isRouteUrlObject} from "blitz"

export * from "./index-browser"

Expand Down Expand Up @@ -130,10 +132,12 @@ export const setupBlitzServer = <TPlugins extends readonly BlitzServerPlugin<obj
plugins,
onError,
logger,
formatError,
}: {
plugins: TPlugins
onError?: (err: Error) => void
logger?: ReturnType<typeof BlitzLogger>
formatError?: (err: Error) => Error
}) => {
initializeLogger(logger ?? BlitzLogger())

Expand Down Expand Up @@ -168,9 +172,9 @@ export const setupBlitzServer = <TPlugins extends readonly BlitzServerPlugin<obj
getClient(),
),
)
} catch (err: any) {
onError?.(err)
throw err
} catch (error: any) {
onError?.(error)
throw formatError?.(error) ?? error
}
}

Expand All @@ -197,9 +201,9 @@ export const setupBlitzServer = <TPlugins extends readonly BlitzServerPlugin<obj
getClient(),
),
)
} catch (err: any) {
onError?.(err)
throw err
} catch (error: any) {
onError?.(error)
throw formatError?.(error) ?? error
}
}

Expand All @@ -215,7 +219,8 @@ export const setupBlitzServer = <TPlugins extends readonly BlitzServerPlugin<obj
])
} catch (error: any) {
onError?.(error)
return res.status(400).send(error)
const formattedError = formatError?.(error) ?? error
return res.status(400).send(formattedError)
}
}

Expand Down
6 changes: 4 additions & 2 deletions packages/blitz-rpc/src/index-server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {assert, baseLogger, Ctx, newLine, prettyMs, ResolverConfig} from "blitz"
import {NextApiRequest, NextApiResponse} from "next"
import {deserialize, serialize as superjsonSerialize, parse} from "superjson"
import {deserialize, parse, serialize as superjsonSerialize} from "superjson"
import {resolve} from "path"
import chalk from "chalk"

Expand Down Expand Up @@ -149,6 +149,7 @@ async function getResolverMap(): Promise<ResolverFiles | null | undefined> {

interface RpcConfig {
onError?: (error: Error) => void
formatError?: (error: Error, ctx: Ctx) => Error
}

export function rpcHandler(config: RpcConfig) {
Expand Down Expand Up @@ -265,7 +266,8 @@ export function rpcHandler(config: RpcConfig) {
error.statusCode = 500
}

const serializedError = superjsonSerialize(error)
const formattedError = config.formatError?.(error, ctx) ?? error
const serializedError = superjsonSerialize(formattedError)

res.json({
result: null,
Expand Down
17 changes: 9 additions & 8 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.