Error Handling in oRPC Clients
This guide explains how to handle type-safe errors in oRPC clients using type-safe error handling. Both server-side and client-side clients are supported.
Using safe and isDefinedError
ts
import { , } from '@orpc/client'
const =
.(.({ : .() }))
.({
: {
: .({ : .() })
}
})
.(async ({ , }) => {
throw .({ : { : 1000 } })
return { : . }
})
.()
const [, , ] = await (({ : '123' }))
// or const { error, data, isDefined } = await safe(doSomething({ id: '123' }))
if (()) { // or isDefined
// handle known error
.(..)
}
else if () {
// handle unknown error
}
else {
// handle success
.()
}INFO
safeworks liketry/catch, but can infer error types.safesupports both tuple[error, data, isDefined]and object{ error, data, isDefined }styles.isDefinedErrorchecks if an error originates from.errors.isDefinedcan replaceisDefinedError
Safe Client
If you often use safe for error handling, createSafeClient can simplify your code by automatically wrapping all procedure calls with safe. It works with both server-side and client-side clients.
ts
import { createSafeClient } from '@orpc/client'
const safeClient = createSafeClient(client)
const [error, data] = await safeClient.doSomething({ id: '123' })