Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 15 additions & 8 deletions packages/typed-express-router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,19 @@ logging.

```ts
const typedRouter = createRouter(MyApi, {
onDecodeError: (errs, req, res) => {
decodeErrorFormatter: (errs, req) => {
// Format `errs` however you want
res.send(400).json({ message: 'Bad request' }).end();
return { message: 'Bad request' };
},
onEncodeError: (err, req, res) => {
getDecodeErrorStatusCode: (errs, req) => {
return 400;
},
encodeErrorFormatter: (err, req) => {
return { message: 'Internal server error' };
},
getEncodeErrorStatusCode: (err, req) => {
// Ideally won't happen unless type safety is violated, so it's a 500
res.send(500).json({ message: 'Internal server error' }).end();
return 500;
},
afterEncodedResponseSent: (status, payload, req, res) => {
// Perform side effects or other things, `res` should be ended by this point
Expand All @@ -92,17 +98,18 @@ const typedRouter = createRouter(MyApi, {

// Override the decode error handler on one route
typedRouter.get('hello.world', [HelloWorldHandler], {
onDecodeError: customHelloDecodeErrorHandler,
decodeErrorFormatter: customHelloDecodeErrorFormatter,
});
```

### Unchecked routes

If you need custom behavior on decode errors that is more involved than just sending an
error response, then the unchecked variant of the router functions can be used. They do
not fail and call `onDecodeError` when a request is invalid. Instead, they will still
populate `req.decoded`, except this time it'll contain the
`Either<Errors, DecodedRequest>` type for route handlers to inspect.
not fail and send a http response using `decodeErrorFormatter` and
`getDecodeErrorStatusCode` when a request is invalid. Instead, they will still populate
`req.decoded`, except this time it'll contain the `Either<Errors, DecodedRequest>` type
for route handlers to inspect.

```ts
// Just a normal express route
Expand Down
Loading