While developing Deno server, I struggled with the middleware implement, especially how to code the several middleware in the root file.
In this article, I code the error handler and logger example.
Version Infomation
deno 1.8.2 (release, x86_64-apple-darwin)
v8 9.0.257.3
typescript 4.2.2
middleware: oak@v6.5.0
The bellows are the middleware files(error handler, logger examples) and app.ts(root file) examples.
errorHandler.ts
Whenever an error is thrown, this middleware handles the error and responds the error object to a client.
More details about error handling, please check "Deno API Server — How to implement Error Handler by oak".
logger.ts
Whenever an error is thrown, this middleware handles the error log and responds the error object to a client.
The point of these middleware implementations is
- use async function
- use try-catch
- execute
await next()
in try part - throwing error object in the last
app.ts
Before executing logger middleware, set the logger level and format, etc.
setLogger
function example is the bellow.
The log format can be set in a handlers
property. In loggers
property, you can set the log level and configure some types of logs, for instance, dev mode and production mode.
To load the log configure, just call getLogger
function in Deno std logger module. If you prefer prod
loggers in the above, call getLogger(prod)
. Easy.
In my code, I call await setLogger(logLebel);
for loading log config. Then execute app.use()
middlewares.
Note that the middlewares are called from the top but they are executed from the bottom. The middleware for router should be called the last.
API Execution Result
When API throws an error in the controller or anywhere, the logger is called first then called error handler next.
You can put console.log
in middleware and check how they are called.