Menu

Error handling — Fastify with TypeScript (part 10/18)
📰

Error handling — Fastify with TypeScript (part 10/18)

DEV Community: fastify·Antonio Tripodi·10 days ago
#xXGhuFRd
#devtofastify#devto#dev#error#users
Long article (1636 words) — no AI summary yet.
Reading 0:00
15s threshold

Error handling

Tenth chapter of the "Fastify with TypeScript" series. Good error handling is what separates a robust API from a fragile one. Our API currently produces errors in three different shapes, and one of them leaks information. Let's fix both by handling every error in one place.

What happens by default

Fastify catches everything that is thrown in a hook or a handler and turns it into a response. To see what that response looks like, make a handler fail. In src/users/users.route.ts , add this as the second line of the GET / handler:

throw new Error ( 'connect ECONNREFUSED db-prod-01:5432 (user "admin")' ) ;

Enter fullscreen mode

Exit fullscreen mode

curl localhost:3000/api/v1/users # {"statusCode":500,"error":"Internal Server Error","message":"connect ECONNREFUSED db-prod-01:5432 (user \"admin\")"}

Enter fullscreen mode

Exit fullscreen mode

The message of an internal error went straight to the client, host name and user included.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.