Files
trpc-nuxt/package/recipes/error-formatting.md
Robert Soriano c7ac9ee09d fix publish issue
2022-05-19 01:20:47 -07:00

889 B

Error Formatting

The error formatting in your router will be inferred all the way to your client (& Vue components).

Adding custom formatting

// ~/server/trpc/index.ts
import * as trpc from '@trpc/server'

export const router = trpc.router<Context>()
  .formatError(({ shape, error }) => {
    return {
      ...shape,
      data: {
        ...shape.data,
        zodError:
          error.code === 'BAD_REQUEST'
          && error.cause instanceof ZodError
            ? error.cause.flatten()
            : null,
      }
    }
  })

Usage in Vue

<script setup lang="ts">
const { error } = await useAsyncQuery(['getUser', { id: 69 }])
</script>

<template>
  <pre v-if="error?.data?.zodError">
    {{ JSON.stringify(error.data.zodError, null, 2) }}
  </pre>
</template>

Learn more about error formatting here.