|
| 1 | +(function() { |
| 2 | + const ErrorStackParser = require('error-stack-parser') |
| 3 | + |
| 4 | + const overlayStyle = { |
| 5 | + position: 'fixed', |
| 6 | + 'box-sizing': 'border-box', |
| 7 | + top: '0px', left: '0px', |
| 8 | + bottom: '0px', right: '0px', |
| 9 | + width: '100vw', height: '100vh', |
| 10 | + 'background-color': 'rgb(200, 0, 0)', |
| 11 | + padding: '2rem', |
| 12 | + 'z-index': 1337, |
| 13 | + 'font-family': 'Menlo, Consolas, monospace', |
| 14 | + color: 'rgb(232, 232, 232)', |
| 15 | + 'white-space': 'pre-wrap' |
| 16 | + } |
| 17 | + |
| 18 | + const headerStyle = { |
| 19 | + 'font-size': 'larger', |
| 20 | + 'font-weight': 'bold' |
| 21 | + } |
| 22 | + |
| 23 | + const traceStyle = { |
| 24 | + 'font-size': '1rem' |
| 25 | + } |
| 26 | + |
| 27 | + function applyStyles(element, styles) { |
| 28 | + element.setAttribute('style', '') |
| 29 | + for (const key in styles) { |
| 30 | + if (!styles.hasOwnProperty(key)) continue |
| 31 | + element.style[key] = styles[key].toString() |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + function render(name, message, frames) { |
| 36 | + // Create container |
| 37 | + const overlay = document.createElement('div') |
| 38 | + applyStyles(overlay, overlayStyle) |
| 39 | + |
| 40 | + // Create header |
| 41 | + const header = document.createElement('div') |
| 42 | + applyStyles(header, headerStyle) |
| 43 | + header.appendChild(document.createTextNode(`${name}: ${message}`)) |
| 44 | + overlay.appendChild(header) |
| 45 | + |
| 46 | + // Show trace |
| 47 | + const trace = document.createElement('div') |
| 48 | + applyStyles(trace, traceStyle) |
| 49 | + for (const frame of frames) { |
| 50 | + const { source } = frame |
| 51 | + const elem = document.createElement('div') |
| 52 | + elem.appendChild(document.createTextNode(source)) |
| 53 | + trace.appendChild(elem) |
| 54 | + } |
| 55 | + overlay.appendChild(trace) |
| 56 | + |
| 57 | + // Mount |
| 58 | + document.body.appendChild(overlay) |
| 59 | + } |
| 60 | + |
| 61 | + function crash(error) { |
| 62 | + let frames = [] |
| 63 | + try { |
| 64 | + frames = ErrorStackParser.parse(error) |
| 65 | + } catch (e) { |
| 66 | + } |
| 67 | + render(error.name, error.message, frames) |
| 68 | + } |
| 69 | + |
| 70 | + window.onerror = function(messageOrEvent, source, lineno, colno, error) { |
| 71 | + if (error == null || !(error instanceof Error) || messageOrEvent.indexOf('Script error') !== -1) { |
| 72 | + crash(new Error('Unknown script error.'))// TODO: more helpful message |
| 73 | + } else { |
| 74 | + crash(error) |
| 75 | + } |
| 76 | + } |
| 77 | +})() |
0 commit comments