How to set up 404 handler in case of a custom express app #155
-
Would it be possible to expose the default 404 handler so it can be used when using a custom express instance to provide a consistent api interface with minimal effort? |
Beta Was this translation helpful? Give feedback.
Replies: 7 comments
-
Hello @Isaac-Leonard , the handler for 404 (Not found) errors can be globally configured when using import {createConfig, createResultHandler} from 'express-zod-api';
const myResultHandler = createResultHandler({
...,
handler: ({error, input, output, request, response, logger}) => {
// your implementation, for example:
if (error && error.status === 404) {
response.status(error.status).end(error.message);
}
}
});
const config = createConfig({
errorHandler: myResultHandler,
...
});
const routing = {...};
createServer(config, routing); In case of the request to a path that is not declared in There is a method import * as express from 'express';
import {createConfig, attachRouting} from 'express-zod-api';
const app = express();
const config = createConfig({app, ...});
const routing = {...};
attachRouting(config, routing);
app.use((req, res) => {
// your 404 handler implementation, for example:
res.status(404).end(`Path ${req.path} not found.`);
});
app.listen(); So the library provides two options:
I hope one of these solutions will suit your needs. Please let me know. If you have any suggestions on how this design can be improved, please also let me know. |
Beta Was this translation helpful? Give feedback.
-
Hello again @Isaac-Leonard
The easiest solution for using the existing // ...
attachRouting(config, routing);
app.use((request, response) => {
// any ResultHandler.handler() of your choice
defaultResultHandler.handler({
request, response,
error: createHttpError(404, `${request.path} not found`),
logger: createLogger(config.logger), // or config.logger in case of custom logger
input: null,
output: null
});
});
app.listen(); So basically it's exposed. The problem currently is the logger instance. If the custom logger is not used then it only exists within |
Beta Was this translation helpful? Give feedback.
-
I think that I can make |
Beta Was this translation helpful? Give feedback.
-
@Isaac-Leonard , I made a PR #154 which I believe will resolve the issue and provide you with at least two options for your case. |
Beta Was this translation helpful? Give feedback.
-
The feature will be released in version 2.6.0. |
Beta Was this translation helpful? Give feedback.
-
the feature has been released in version 2.6.0. Please upgrade and so can do the following: const {notFoundHandler} = attachRouting(config, routing);
app.use(notFoundHandler);
app.listen(); |
Beta Was this translation helpful? Give feedback.
-
Hi @RobinTail |
Beta Was this translation helpful? Give feedback.
@Isaac-Leonard ,
the feature has been released in version 2.6.0. Please upgrade and so can do the following: