zsa provides an experimental feature that allows you to shape and customize the error object returned by your server actions. This feature enables you to include additional information or modify the structure of the error object to better suit your application's needs.
This feature is experimental and we may change the API in the future.
To shape the error object, you can use the experimental_shapeError method when creating a server action or procedure. This method takes a callback function that receives the err (the original error object) and typedData (an object containing the parsed and raw input data) as arguments.
The callback function should return an object that represents the desired shape of the error.
Make sure to not return any vulnerable data in your custom errors such as stack traces or sensitive information.
You are probably going to define your shape error functions before Typescript will have access to the input/output schemas of your actions.
To get around this, you can use the typedData object that is passed to the shape error function. This object contains the parsed and raw input data of the action.
When using typedData, it must be returned as values in an object. So for example, you can't return typedData.inputRaw as the error, but you can return an object such as { values: typedData.inputRaw }.
Shaped errors can be chained together when using procedures. When shaping an error in a procedure, you have access to the ctx object from the previous chained error.
Here's an example of how you can use the custom error shaping feature with React Hook Form:
In this example, we shape the error object to include rhfErrors and values properties, which can be used directly with React Hook Form.
By shaping the error object, you can easily integrate it with React Hook Form, providing default values and error messages based on the error object.
The custom error shaping feature in zsa provides flexibility in structuring error objects to meet your application's specific needs, making it easier to handle and display errors in your user interface.