oRPC is currently pre-stable, please report any issues on our Discord or GitHub 🚧
oRPC
background

Typesafe Error Handling

How to intercept, handle or log errors inside oRPC

Typed errors

import {  } from '@orpc/react-query'
import { , , , ,  } from '@orpc/server'
 
const  = 
  .({
    : {
      : 409, // (optional) default CONFLICT is 409
      : 'Conflict', // (optional)
      : .({ // (optional)
        : .(),
      }),
    },
    // ANY_CODE: { unknown code is allowed, with default status is 500
    //   status: 500,
    // },
  })
  .(({  }) => {
    throw .({ : { : 'some reason' } })
 
    // is the same as, but this is not typed
    throw new ({ : 'CONFLICT', : { : 'some reason' } })
 
    // throw errors.ANY_CODE()
  })
 
const  = () // or any kind of client
 
const [, , ] = await (({ : 'title' }))
 
if () {
  if (()) { // or use isDefined const
    const  = . // { why: 'some reason' } full typed data
  }
  else {
    // any errors what not satisfy, or not defined in .errors
  }
}
 
/// example handle error for `@orpc/react-query`
 
import {  } from '@tanstack/react-query'
import {  } from 'zod'
 
const  = ()
 
const  = (.({
  () {
    if (()) {
      const  = . // { why: 'some reason' } full typed data
    }
  },
}))

Note: typesafe errors are coverage in every oRPC packages: @orpc/client, @orpc/react-query, @orpc/vue-query, @orpc/vue-colada, ... Please use isDefinedError or safe to typesafe handle errors. Export from @orpc/contract, @orpc/server, and @orpc/client.

Handle errors

import { ,  } from '@orpc/server'
 
const  = 
    .(async ({ , ,  }, ) => {
        try {
            const  = await ({})
            const  = . // do something on success
            return 
        } catch () {
            // do something on error
            throw 
        } finally {
            // do something on finish
        }
    })
    .(({ ,  }) => {
        throw new ({
            : 'NOT_FOUND',
            : 'Not found',
            : 404, // Optional: custom default behavior
            : { : 'include in the body and send to the client' } // pass data to the client
        })
    })

On this page