Error Handling
In ZSA, errors are handled using the ZSAError
class. This class extends the built-in Error
class and adds some additional properties to make it easier to handle errors in your server actions.
Throwing Errors
Just throw a string!
If all you care about is the error message, you can just throw a string:
This string will be accessible in the data
property of the error object.
Throw a ZSAError
To throw an error in a server action with a code, you can simply throw a new instance of the ZSAError
class:
The first argument to the ZSAError
constructor is the error code, and the second argument is the error data. The error data can be any value, but it is typically a string or an object.
If the error data is an instance of the built-in Error
class, the ZSAError
instance will inherit the message
, name
, and cause
properties from the error data.
If the error data is a string and the message
property is not set, the message
property will be set to the error data.
Error Codes
ZSA defines a set of error codes that can be used to identify the type of error that occurred. These error codes are defined in the ERROR_CODES
enum:
Typed Errors
ZSA also provides a typed version of the ZSAError
class called TZSAError
. This class is a generic type that takes a Zod schema as a type parameter. The schema represents the input schema of the server action.
If the error code is INPUT_PARSE_ERROR
, the TZSAError
instance will have additional properties that provide information about the validation errors that occurred:
fieldErrors
: An object that maps field names to arrays of error messages.formErrors
: An array of error messages that apply to the entire form.formattedErrors
: A formatted version of the validation errors.
These properties are inferred from the Zod schema that is passed to the TZSAError
type.
Handling Errors
When calling a server action, you can handle errors by destructuring the result and checking for an error:
By using the error code and the additional error properties, you can handle different types of errors in different ways.
OpenAPI Error Status Codes
zsa-openapi
maps ZSA error codes to HTTP status codes. This can be useful when returning errors from an API endpoint: