Edgio

Error Handling

This guide covers how to handle origin errors at the edge to display custom error pages or retry requests from a different origin.
The examples found in this guide can be found in the edgio-v7-error-handling-example repository.

The catch method

EdgeJS provides a catch method that you can use to responses that result in an error. There are two main ways to use this method:

Displaying a custom error page

In this example we catch all responses with a 5xx status code and serve a static error page with a 500 status code:
JavaScript
1import {Router} from '@edgio/core';
2
3export default new Router()
4 .get('/500', ({serveStatic}) => {
5 // Serve a static error page with a 500 status code
6 serveStatic('public/500.html', {
7 statusCode: 500,
8 });
9 })
10 .catch(/^5.*/, {
11 // Match all responses with a 5xx status code and redirect internally to /500
12 response: {
13 set_status_code: 302, // redirect
14 },
15 headers: {
16 set_response_headers: {
17 location: '%{scheme}://%{host}/500', // Set the path to /500
18 },
19 },
20 // This makes the redirect invisible to the client. They will just see the 500.html page.
21 // You can leave this out to send the redirect all the way back to the client.
22 url: {
23 follow_redirects: true,
24 },
25 });

Retrying the request from a different origin

In this example, we have a legacy origin that we want to use as a fallback if the primary origin returns a 5xx status code. Assuming you have an origin called “legacy” configured in your edgio.config.js file, you can use the set_origin option to retry the request from the legacy origin:
JavaScript
1import {Router} from '@edgio/core';
2
3export default new Router()
4 .get('/legacy/:path*', {
5 origin: {
6 // This will retry the request from the legacy origin if the primary origin returns a 5xx status code
7 set_origin: 'legacy',
8 },
9 url_rewrite: [
10 // strip the "/legacy" prefix from the path
11 {source: '/legacy/(.*)', syntax: 'regexp', destination: '/$1'},
12 ],
13 })
14 .match(
15 // Redirect all 5xx responses to the same path with "/legacy" prepended (unless we already have a "/legacy" in the path)
16 {path: {not: /^\/legacy\/.*/}, response: {status_code: /5.*/}},
17 {
18 response: {
19 set_status_code: 302,
20 },
21 url: {
22 // This makes the redirect invisible to the client. They will just see the 500.html page.
23 follow_redirects: true,
24 },
25 headers: {
26 set_response_headers: {
27 // Redirect to the same URL with "/legacy" prepended
28 location:
29 '%{scheme}://%{host}/legacy%{path}%{is_args}%{query_string}',
30 },
31 },
32 }
33 );
Note that here we use match({ response: { status_code: /5.*/}}). This is equivalent to catch(/5.*/) but allows us to add an additional criteria to exclude paths starting with “/legacy” from being retried.