DefaultHandlers
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.
HTTP Status Code Range | status Field Value | Description |
---|---|---|
1xx, 2xx, 3xx | "success" | Successful requests or informational responses. |
4xx | "fail" | Client-side errors. |
5xx | "error" | Server-side errors. |
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 anHttp.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 aProtocol
object (but not anHttp.End
instance), it’s wrapped in anHttp.End
object. - If
output
is anHttp.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.