Error handling using Edge Workers
This example translates a HTTP 503 status code (service unavailable) coming from an overloaded origin into a HTML page presenting the information in a more user friendly way. It also includes javascript to retry after the period indicated by the 'Retry-After' header coming from origin, if present. Otherwise it'll retry after a default number of seconds. Note that even if the content from origin is dynamic it makes sense to configure the property such that the HTTP error responses are cached at least for a short duration..
Outcome : Page Displaying error handling
Below is the code snippet in main.js
/*
(c) Copyright 2019 Akamai Technologies, Inc. Licensed under Apache 2 license.
Version: 0.1
Purpose: Present a useful error page to the user, instead of a plain 503, and include js to automatically retry after the period indicated in the 'Retry-After' header.
Repo: https://github.com/akamai/edgeworkers-examples/tree/master/origin-overload
*/
/*
onOriginResponse: This event happens as the origin response is created.
The event only happens if the response is not served from cache and not constructed on the edge.
Use this event if you want to modify the response before it is cached.
*/
export function onOriginResponse (request, response) {
response.addHeader('Origin-Response-Status', response.status);
if (response.status === 503 || response.status === 500) {
var retry = parseInt(response.getHeader('Retry-After')) || 10;
request.respondWith(200, { 'Content-Type': ['text/html'] }, ' The origin server is currently overloaded, please retry in ' + retry + ' seconds ');
}
}