Skip to main content
Suvidha provides default handlers that manage the request/response lifecycle. These handlers support Http classes and plain Protocol objects for responses. You can customize the format of the response body using a formatter function.

The Formatter Function

The Formatter function is used to structure the final HTTP response body. It takes the status code, body, and metadata as arguments, and returns the formatted response body.
Suvidha provides a default formatter:
The default formatter creates a { status, data, meta } object that maps HTTP status codes. You can specify a custom formatter when creating DefaultHandlers:

DefaultHandlers Class

The DefaultHandlers class implements the Handlers interface and provides default implementations for handling errors, schema errors, successful responses, and post-response actions. It sets the Content-Type to application/json by default.

onErr(err: unknown, conn: Conn)

Handles errors.
  • If err is an Http.End instance, it sends the response with the specified status code, headers, and body (formatted by the formatter).
  • Otherwise, it sends a 500 Internal Server Error response with a default message.

onSchemaErr(err: ZodError, conn: Conn, next: NextFunction)

Handles schema validation errors using Zod. It always throws an Http.BadRequest error with a default message.

onComplete(output: unknown, conn: Conn)

Handles successful responses.
  • If output is a Protocol object (but not an Http.End instance), it’s wrapped in an Http.End object.
  • If output is an Http.End instance, it sends the response with the specified status code, headers, and body (formatted by the formatter).
  • If output is a primitive type (string, number, boolean, undefined(converted to null), object, or null), it sends a 200 OK response with the output as the body (formatted by the formatter).
  • Otherwise, it logs an error and throws a Http.InternalServerError exception.

onPostResponse(data: unknown, conn: Conn)

Called after a response has been sent (headers already sent). It is primarily used for logging or cleanup. The default implementation logs the response data.