How to custom response 408 timeout on spesific route?
Hi sir,
I used this to handle the response timeout in totaljs 3,
ROUTE('#408', function () {
var self = this;
self.json({ code: 408, message: 'Error timeout!'});
});
That will return same timeout response for all routes and that's OK.
Right now, I want to custom the response timeout only to spesific route, but the other routes still using default timeout response like above?
Is this possible? How to do this in TotalJS 3?
Thanks for your help.
@aalfiann Each route can have its own timeout. But 409 means conflict, not a timeout. However, in this route you create a custom response based on a URL address, e.g. self.url or self.uri {URI object}.
sorry, I mean 408 timeout.
Yes, I was thinking to do like that, but I couldn't determine if the status is 408 and return the custom response timeout.
Here is my controller
exports.install = function () {
ROUTE('/test', viewIndex)
ROUTE('/test/contact', viewContact)
ROUTE('/test/timeout', testTimeout, ['get', 5000]) // this request will timeout for 5 seconds
}
function viewIndex () {
const self = this
self.view('index')
}
function viewContact () {
const self = this
self.view('contact')
}
function _blockingTest (ms) {
ms = (ms === undefined ? 1000 : ms)
const start = Date.now()
const time = start + ms
while (Date.now() < time) {
// empty progress
}
return start
}
function testTimeout () {
const self = this
// try to blocking request for 10 seconds so this will get timout
_blockingTest(10000)
self.view('index')
}
I found that timeout is not working?
Your _blockingTest function is blocking entire application and the framework can't even process any timeouts.
Try to use bellow code instead:
function testTimeout () {
setTimeout(() => this.view('index'), 10000);
}
@molda , thanks the timeout working well.
now, how to handle the timeout to using the custom timeout response?
function testTimeout () {
// try to blocking request for 10 seconds so this will get timout
setTimeout(() => this.view('index'), 10000)
// if the timeout happened, set custom timeout response
// code below here not work, it giving response directly
// var self = this;
// self.json({ code: 408, message: 'This is Custom Error timeout!'});
}
Thanks, I solved this by put condition on route default
ROUTE('#408', function () {
const self = this
if (self.req.uri.path === '/test/timeout') {
self.json({ code: 408, message: 'This is custom error timeout!' })
} else {
self.json({ code: 408, message: 'Error timeout!' })
}
})
found new issue, why the status return 200 ?
when I set self.status = 408 it cause the browser looping.
In your code in ROUTE('#408', you still need to set the status.
So before self.json(.. add self.status = 408;