mm-ninja-turtles / turtle-express

My attempt of making Express.JS a typesafe router with Zod.
3 stars 0 forks source link

[feature]: handle unexpected error #22

Closed wai-lin closed 2 years ago

wai-lin commented 2 years ago

Problem

Currently internal handler generator function does not try, catch or promise, catch when unexpected happens. It should be gracefully fall to catch block and response back with 500 automatically.

Solution

There's an official guide from express on how to handle errors. Using one of those solution should fix this.

wai-lin commented 2 years ago

My decision after reading the express's error handling examples is that turtle-express will fallback the errors to the express level and expose opinionated error handler function which users can override or write their own custom error handler.

import { createRouter, errorHandler } from 'turtle-express'

// ...

users.handler({
  method: 'get',
  response: {
    200: z.any(),
  },
  resolver() {
    throw new Error('hey! here\'s the error');
  }
})

router.setup(app, { paths: [users] })

// should declare after everything and before `app.listen`
app.use(errorHandler)

// ...
app.listen(port, () => {
// ...