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.…