In Opine, to handle error, we need to create a special middleware that is able to receive four argument - error, request, response, and next objects. This middileware must be lastly used after all middlewares in the HTTP request cycle.
// main.ts
import {opine,serveStatic} from "https://deno.land/x/opine@2.2.0/mod.ts"
const app = opine()
app.use(serveStatic("public"))
import indexRouter from './routes/index.ts'
app.use('/',indexRouter)
app.use((err, req, res, next)=>{
console.error(err.stack)
res.setStatus(500).send('Something broke!')
})
app.listen(3000)
console.log("Opine started on port 3000")
// routes/index.ts
import {Router} from "https://deno.land/x/opine@2.2.0/mod.ts"
const indexRouter = Router()
const getDate = (req,res,next)=>{
const date = (new Date()).toLocaleDateString('it-IT')
req.date = date
next()
}
indexRouter.use(getDate)
indexRouter.get('/', (req,res)=>{
res.send(`Today is ${req.date}`)
})
indexRouter.get('/post/:id', (req,res)=>{
res.send(`The id of the post is ${req.params.id}`)
})
export default indexRouter