diff --git a/js/app.js b/js/app.js index 520bedbd..9e8e3a91 100644 --- a/js/app.js +++ b/js/app.js @@ -5,6 +5,8 @@ require('babel/polyfill'); import React from 'react'; import { Router, Redirect } from 'react-router'; import history from './history'; +import { ReactError, ResourceNotFoundError } from './react_error.js'; +import { ResourceNotFoundErrorHandler } from './react_error_handlers'; /* eslint-disable */ import fetch from 'isomorphic-fetch'; @@ -91,12 +93,20 @@ class AppGateway { // us in that case. history.listen(EventActions.routeDidChange); - React.render(( - - {redirectRoute} - {getRoutes(type, subdomain)} - - ), document.getElementById('main')); + ReactError({ + render: React.render, + params: [( + + {redirectRoute} + {getRoutes(type, subdomain)} + + ), + document.getElementById('main')], + errors: [{ + error: ResourceNotFoundError, + handler: ResourceNotFoundErrorHandler + }] + }); // Send the applicationDidBoot event to the third-party stores EventActions.applicationDidBoot(settings); diff --git a/js/react_error.js b/js/react_error.js new file mode 100644 index 00000000..61fb4a70 --- /dev/null +++ b/js/react_error.js @@ -0,0 +1,42 @@ +'use strict'; + +function _transformErrorsListToHashMap(errors) { + return errors.reduce((errObj, { error, handler }) => { + const errorName = error.name; + if(!errObj[errorName]) { + errObj[errorName] = { + error: error, + handler: handler + }; + return errObj; + } else { + throw new Error('You\'re trying to override the error handler for ' + errorName + ' by specifying it twice.'); + } + }, {}); +} + +export function ReactError({ render, params, errors }) { + errors = _transformErrorsListToHashMap(errors); + try { + // use react's render function + parameters to render + // the application + render(...params); + } catch(err) { + const potErrorRoutine = errors[err.name]; + if(potErrorRoutine) { + potErrorRoutine.handler(err); + } else { + console.error(err.stack); + } + } +} + +// Followed: http://stackoverflow.com/a/32749533/1263876 for extending errors +export class ResourceNotFoundError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + this.message = message; + Error.captureStackTrace(this, this.constructor.name); + } +} \ No newline at end of file diff --git a/js/react_error_handlers.js b/js/react_error_handlers.js new file mode 100644 index 00000000..57366603 --- /dev/null +++ b/js/react_error_handlers.js @@ -0,0 +1,5 @@ +'use strict'; + +export function ResourceNotFoundErrorHandler() { + console.log(arguments); +} \ No newline at end of file