VergeStackVergeStack

Error Handling

Custom error classes are available for throwing specific errors within your actions or routes. These helpers provide more meaningful and standardized error responses across your application while following the familiar throw new Error() pattern.

Available Custom Errors

The following custom error classes are available:

Error ClassCodeDescription
UnauthorizedError401Used when authentication is required but not provided or is invalid.
ForbiddenError403Used when the authenticated user doesn't have permission to access a resource.
BadRequestError400Used when the request is malformed or contains invalid data.
NotFoundError404Used when a requested resource is not found.
VisibleInternalError500Used for internal server errors that can be safely exposed to the client.

All other errors (including the native Error) are treated as internal server errors and are not exposed to the client.

Each error class shares the same common behavior, differing only in the status property. This determines the specific HTTP status code returned in the error response.

Usage

Here's an example of how to use the UnauthorizedError and ForbiddenError classes in an action or route:

import { UnauthorizedError, ForbiddenError } from '@vergestack/api';
 
export const authAction = createAction()
  .input(z.void())
  .output(z.void())
  .handler(async () => {
    if (!isUserAuthenticated()) {
      throw new UnauthorizedError('User is not authenticated');
    }
 
    if (!userHasAccess()) {
      throw new ForbiddenError('User does not have access');
    }
 
    // ... rest of the action logic
  });

Built-in Error Handling

The framework handles the following errors automatically:

Error TypeStatus Code
Input validation errors400 BAD_REQUEST
Output validation errors500 INTERNAL_SERVER_ERROR
Native errors500 INTERNAL_SERVER_ERROR
export const errorAction = createAction()
  .input(z.void())
  .output(z.void())
  .handler(async () => {
    throw new Error('This is a native error');
  });

On this page