or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

container-management.mddefault-logger.mdexception-rejection-handling.mdformats.mdindex.mdlogger-management.mdprofiling.mdtransports.md

exception-rejection-handling.mddocs/

0

# Exception and Rejection Handling

1

2

Automatic handling of uncaught exceptions and unhandled promise rejections with configurable transports and exit behavior.

3

4

## Capabilities

5

6

### Exception Handler

7

8

Class for handling uncaught exceptions in Node.js applications with configurable logging transports.

9

10

```javascript { .api }

11

/**

12

* Handler for uncaught exceptions

13

*/

14

class ExceptionHandler {

15

constructor(logger: Logger);

16

17

/** Associated logger instance */

18

logger: Logger;

19

/** Map of registered transport handlers */

20

handlers: Map<any, any>;

21

/** Exception catcher function or boolean flag */

22

catcher: Function | boolean;

23

}

24

```

25

26

### Exception Handling Methods

27

28

Methods for configuring and managing exception handling behavior.

29

30

```javascript { .api }

31

/**

32

* Add transports to handle uncaught exceptions

33

* @param transports - Transport instances or arrays of transports

34

*/

35

handle(...transports: Transport[]): void;

36

37

/**

38

* Remove transports from exception handling

39

* @param transports - Transport instances or arrays of transports

40

*/

41

unhandle(...transports: Transport[]): void;

42

43

/**

44

* Get comprehensive information about an exception

45

* @param err - Error string or Error object

46

* @returns Object containing error details

47

*/

48

getAllInfo(err: string | Error): object;

49

50

/**

51

* Get current process information

52

* @returns Object containing process details

53

*/

54

getProcessInfo(): object;

55

56

/**

57

* Get operating system information

58

* @returns Object containing OS details

59

*/

60

getOsInfo(): object;

61

62

/**

63

* Get stack trace information from error

64

* @param err - Error object

65

* @returns Object containing stack trace details

66

*/

67

getTrace(err: Error): object;

68

```

69

70

**Usage Examples:**

71

72

```javascript

73

const winston = require('winston');

74

75

const logger = winston.createLogger({

76

transports: [

77

new winston.transports.Console(),

78

new winston.transports.File({ filename: 'app.log' })

79

]

80

});

81

82

// Handle exceptions with specific transports

83

logger.exceptions.handle(

84

new winston.transports.File({ filename: 'exceptions.log' }),

85

new winston.transports.Console({

86

format: winston.format.combine(

87

winston.format.timestamp(),

88

winston.format.errors({ stack: true }),

89

winston.format.json()

90

)

91

})

92

);

93

94

// Remove exception handling

95

logger.exceptions.unhandle(

96

new winston.transports.Console()

97

);

98

99

// Custom exception information

100

process.on('uncaughtException', (err) => {

101

const info = logger.exceptions.getAllInfo(err);

102

console.log('Exception details:', info);

103

});

104

```

105

106

### Rejection Handler

107

108

Class for handling unhandled promise rejections with configurable logging transports.

109

110

```javascript { .api }

111

/**

112

* Handler for unhandled promise rejections

113

*/

114

class RejectionHandler {

115

constructor(logger: Logger);

116

117

/** Associated logger instance */

118

logger: Logger;

119

/** Map of registered transport handlers */

120

handlers: Map<any, any>;

121

/** Rejection catcher function or boolean flag */

122

catcher: Function | boolean;

123

}

124

```

125

126

### Rejection Handling Methods

127

128

Methods for configuring and managing promise rejection handling behavior.

129

130

```javascript { .api }

131

/**

132

* Add transports to handle unhandled promise rejections

133

* @param transports - Transport instances or arrays of transports

134

*/

135

handle(...transports: Transport[]): void;

136

137

/**

138

* Remove transports from rejection handling

139

* @param transports - Transport instances or arrays of transports

140

*/

141

unhandle(...transports: Transport[]): void;

142

143

/**

144

* Get comprehensive information about a rejection

145

* @param err - Error string or Error object

146

* @returns Object containing rejection details

147

*/

148

getAllInfo(err: string | Error): object;

149

150

/**

151

* Get current process information

152

* @returns Object containing process details

153

*/

154

getProcessInfo(): object;

155

156

/**

157

* Get operating system information

158

* @returns Object containing OS details

159

*/

160

getOsInfo(): object;

161

162

/**

163

* Get stack trace information from error

164

* @param err - Error object

165

* @returns Object containing stack trace details

166

*/

167

getTrace(err: Error): object;

168

```

169

170

**Usage Examples:**

171

172

```javascript

173

const winston = require('winston');

174

175

const logger = winston.createLogger({

176

transports: [

177

new winston.transports.Console(),

178

new winston.transports.File({ filename: 'app.log' })

179

]

180

});

181

182

// Handle promise rejections

183

logger.rejections.handle(

184

new winston.transports.File({ filename: 'rejections.log' }),

185

new winston.transports.Console({

186

format: winston.format.combine(

187

winston.format.timestamp(),

188

winston.format.errors({ stack: true }),

189

winston.format.json()

190

)

191

})

192

);

193

194

// Remove rejection handling

195

logger.rejections.unhandle(

196

new winston.transports.File({ filename: 'rejections.log' })

197

);

198

```

199

200

### Global Exception and Rejection Handling

201

202

Methods available on the winston module for handling exceptions and rejections with the default logger.

203

204

```javascript { .api }

205

/**

206

* Handle uncaught exceptions with default logger

207

* @param transports - Transport instances for exception logging

208

*/

209

function handleExceptions(...transports: Transport[]): void;

210

211

/**

212

* Stop handling uncaught exceptions with default logger

213

* @param transports - Transport instances to remove

214

*/

215

function unhandleExceptions(...transports: Transport[]): void;

216

217

/**

218

* Handle unhandled promise rejections with default logger

219

* @param transports - Transport instances for rejection logging

220

*/

221

function handleRejections(...transports: Transport[]): void;

222

223

/**

224

* Stop handling unhandled promise rejections with default logger

225

* @param transports - Transport instances to remove

226

*/

227

function unhandleRejections(...transports: Transport[]): void;

228

```

229

230

**Usage Examples:**

231

232

```javascript

233

const winston = require('winston');

234

235

// Configure default logger first

236

winston.add(new winston.transports.Console());

237

238

// Handle exceptions globally

239

winston.handleExceptions(

240

new winston.transports.File({ filename: 'exceptions.log' })

241

);

242

243

// Handle rejections globally

244

winston.handleRejections(

245

new winston.transports.File({ filename: 'rejections.log' })

246

);

247

248

// Stop handling

249

winston.unhandleExceptions();

250

winston.unhandleRejections();

251

```

252

253

### Logger Configuration with Exception Handling

254

255

Configure exception and rejection handling during logger creation.

256

257

```javascript { .api }

258

interface LoggerOptions {

259

/** Automatically handle uncaught exceptions */

260

handleExceptions?: boolean;

261

/** Automatically handle unhandled promise rejections */

262

handleRejections?: boolean;

263

/** Specific transports for exception handling */

264

exceptionHandlers?: Transport[];

265

/** Specific transports for rejection handling */

266

rejectionHandlers?: Transport[];

267

}

268

```

269

270

**Usage Examples:**

271

272

```javascript

273

const winston = require('winston');

274

275

// Logger with built-in exception/rejection handling

276

const logger = winston.createLogger({

277

level: 'info',

278

format: winston.format.combine(

279

winston.format.timestamp(),

280

winston.format.errors({ stack: true }),

281

winston.format.json()

282

),

283

transports: [

284

new winston.transports.Console(),

285

new winston.transports.File({ filename: 'app.log' })

286

],

287

handleExceptions: true,

288

handleRejections: true,

289

exceptionHandlers: [

290

new winston.transports.File({ filename: 'exceptions.log' })

291

],

292

rejectionHandlers: [

293

new winston.transports.File({ filename: 'rejections.log' })

294

]

295

});

296

297

// Exit behavior configuration

298

logger.exitOnError = false; // Don't exit on handled exceptions

299

```

300

301

### Advanced Exception Handling Patterns

302

303

**Custom exception processing:**

304

305

```javascript

306

const winston = require('winston');

307

308

class CustomExceptionHandler {

309

constructor() {

310

this.logger = winston.createLogger({

311

transports: [

312

new winston.transports.File({ filename: 'app.log' })

313

]

314

});

315

316

// Custom exception handling

317

this.logger.exceptions.handle(

318

new winston.transports.File({

319

filename: 'exceptions.log',

320

format: winston.format.combine(

321

winston.format.timestamp(),

322

winston.format.printf(({ timestamp, level, message, stack }) => {

323

return `${timestamp} [${level.toUpperCase()}]: ${message}\n${stack}`;

324

})

325

)

326

})

327

);

328

329

// Custom rejection handling

330

this.logger.rejections.handle(

331

new winston.transports.File({

332

filename: 'rejections.log',

333

format: winston.format.combine(

334

winston.format.timestamp(),

335

winston.format.json()

336

)

337

})

338

);

339

}

340

341

setupGlobalHandlers() {

342

// Additional custom handling

343

process.on('uncaughtException', (err) => {

344

const info = this.logger.exceptions.getAllInfo(err);

345

console.error('Uncaught Exception:', info);

346

347

// Custom notification logic

348

this.notifyAdministrators(err);

349

350

// Graceful shutdown

351

setTimeout(() => process.exit(1), 1000);

352

});

353

354

process.on('unhandledRejection', (reason, promise) => {

355

const info = this.logger.rejections.getAllInfo(reason);

356

console.error('Unhandled Rejection at:', promise, 'reason:', info);

357

358

// Custom handling logic

359

this.handleRejection(reason, promise);

360

});

361

}

362

363

notifyAdministrators(error) {

364

// Implementation for admin notification

365

console.log('Notifying administrators of error:', error.message);

366

}

367

368

handleRejection(reason, promise) {

369

// Implementation for custom rejection handling

370

console.log('Handling rejection:', reason);

371

}

372

}

373

374

const exceptionHandler = new CustomExceptionHandler();

375

exceptionHandler.setupGlobalHandlers();

376

```

377

378

**Production-ready exception handling:**

379

380

```javascript

381

const winston = require('winston');

382

383

const createProductionLogger = () => {

384

return winston.createLogger({

385

level: 'info',

386

format: winston.format.combine(

387

winston.format.timestamp(),

388

winston.format.errors({ stack: true }),

389

winston.format.json()

390

),

391

transports: [

392

new winston.transports.File({

393

filename: 'app.log',

394

maxsize: 5242880, // 5MB

395

maxFiles: 10

396

})

397

],

398

handleExceptions: true,

399

handleRejections: true,

400

exceptionHandlers: [

401

new winston.transports.File({

402

filename: 'exceptions.log',

403

maxsize: 5242880,

404

maxFiles: 5

405

})

406

],

407

rejectionHandlers: [

408

new winston.transports.File({

409

filename: 'rejections.log',

410

maxsize: 5242880,

411

maxFiles: 5

412

})

413

],

414

exitOnError: false

415

});

416

};

417

418

const logger = createProductionLogger();

419

420

// Graceful shutdown handling

421

process.on('SIGTERM', () => {

422

logger.info('SIGTERM received, shutting down gracefully');

423

logger.close();

424

process.exit(0);

425

});

426

427

process.on('SIGINT', () => {

428

logger.info('SIGINT received, shutting down gracefully');

429

logger.close();

430

process.exit(0);

431

});

432

```