or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

body-parsing.mdcli.mderror-management.mdindex.mdresponse-handling.mdserver.md

response-handling.mddocs/

0

# Response Handling

1

2

Response sending utilities with automatic content-type detection and error response management for HTTP microservices.

3

4

## Capabilities

5

6

### Send Function

7

8

Sends HTTP responses with automatic content-type detection and proper headers for different data types.

9

10

```typescript { .api }

11

/**

12

* Sends HTTP response with automatic content-type detection

13

* @param res - Node.js ServerResponse object

14

* @param code - HTTP status code (required)

15

* @param obj - Data to send (optional, defaults to null for empty response)

16

*/

17

function send(res: ServerResponse, code: number, obj?: unknown): void;

18

```

19

20

**Automatic Content-Type Handling:**

21

- `null/undefined`: Empty response with no content

22

- `Buffer`: `application/octet-stream` with Content-Length

23

- `Stream`: `application/octet-stream`, pipes stream to response

24

- `Object/Array`: `application/json; charset=utf-8` with JSON serialization

25

- `String`: Text response with Content-Length

26

- `Number`: Converted to string with Content-Length

27

28

**Usage Examples:**

29

30

```typescript

31

import { send } from "micro";

32

33

const handler = async (req, res) => {

34

// JSON response

35

send(res, 200, { message: "Success", data: [1, 2, 3] });

36

37

// Text response

38

send(res, 200, "Hello World");

39

40

// Buffer response

41

send(res, 200, Buffer.from("Binary data"));

42

43

// Empty response

44

send(res, 204); // or send(res, 204, null);

45

46

// Error response

47

send(res, 400, { error: "Bad Request", code: "INVALID_INPUT" });

48

};

49

50

// Stream response

51

import fs from "fs";

52

53

const fileHandler = async (req, res) => {

54

const stream = fs.createReadStream("./large-file.pdf");

55

send(res, 200, stream);

56

57

// Handle stream errors

58

stream.on('error', (err) => {

59

send(res, 500, { error: "File read error" });

60

});

61

};

62

```

63

64

### Send Error Function

65

66

Specialized function for sending error responses with automatic status code handling and development/production error visibility.

67

68

```typescript { .api }

69

/**

70

* Sends error responses with status code and message handling

71

* @param req - Incoming HTTP request (for logging context)

72

* @param res - HTTP response object

73

* @param errorObj - Error object to send (Error or HttpError)

74

*/

75

function sendError(req: IncomingMessage, res: ServerResponse, errorObj: Error | HttpError): void;

76

```

77

78

**Error Handling Behavior:**

79

- Uses `errorObj.statusCode` if available, otherwise defaults to 500

80

- Sends error message as response body

81

- Logs error stack to console with `console.error`

82

- In development mode (NODE_ENV=development), includes stack traces in response

83

84

**Usage Examples:**

85

86

```typescript

87

import { sendError, createError, HttpError, json } from "micro";

88

89

const handler = async (req, res) => {

90

try {

91

// Some operation that might fail

92

throw new Error("Database connection failed");

93

} catch (error) {

94

// Send generic error

95

sendError(req, res, error as Error);

96

return;

97

}

98

};

99

100

// With HTTP status codes

101

const validationHandler = async (req, res) => {

102

try {

103

const data = await json(req);

104

if (!data.email) {

105

const error = createError(400, "Email is required", new Error("Missing email"));

106

sendError(req, res, error);

107

return;

108

}

109

return { success: true };

110

} catch (error) {

111

sendError(req, res, error as Error);

112

}

113

};

114

115

// Custom error handling

116

const customHandler = async (req, res) => {

117

try {

118

// Your code here

119

} catch (error) {

120

if (error instanceof HttpError && error.statusCode === 429) {

121

// Custom handling for rate limit errors

122

send(res, 429, {

123

error: "Rate limited",

124

retryAfter: 60

125

});

126

} else {

127

sendError(req, res, error as Error);

128

}

129

}

130

};

131

```

132

133

## Response Examples

134

135

### JSON API Response

136

137

```typescript

138

const apiHandler = async (req, res) => {

139

const users = await getUsers();

140

141

send(res, 200, {

142

data: users,

143

pagination: {

144

page: 1,

145

limit: 10,

146

total: users.length

147

},

148

meta: {

149

timestamp: new Date().toISOString(),

150

version: "1.0"

151

}

152

});

153

};

154

```

155

156

### File Download Response

157

158

```typescript

159

import fs from "fs";

160

import path from "path";

161

162

const downloadHandler = async (req, res) => {

163

const filePath = path.join(__dirname, "files", "document.pdf");

164

165

if (!fs.existsSync(filePath)) {

166

send(res, 404, { error: "File not found" });

167

return;

168

}

169

170

// Set additional headers before sending

171

res.setHeader("Content-Disposition", "attachment; filename=document.pdf");

172

res.setHeader("Content-Type", "application/pdf");

173

174

const stream = fs.createReadStream(filePath);

175

send(res, 200, stream);

176

};

177

```

178

179

### Conditional Response

180

181

```typescript

182

const conditionalHandler = async (req, res) => {

183

const { format } = req.url?.includes("?")

184

? new URLSearchParams(req.url.split("?")[1])

185

: new URLSearchParams();

186

187

const data = { message: "Hello", timestamp: Date.now() };

188

189

switch (format) {

190

case "xml":

191

res.setHeader("Content-Type", "application/xml");

192

send(res, 200, `<response><message>${data.message}</message></response>`);

193

break;

194

case "text":

195

send(res, 200, `${data.message} at ${data.timestamp}`);

196

break;

197

default:

198

send(res, 200, data); // JSON

199

}

200

};

201

```