componentDidCatch is not called on throw












0















I've tried to use error boundaries to handle errors in my app, but for some reason the componentDidCatch is not called when an error is thrown. I've simplified my app to the example from the react documentation, but it still doesn't work.



My react version is 16.6.3.



ErrorHandler.js



import React from 'react';

export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}

componentDidCatch(error, errorInfo) {
console.log('catch called')
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}

render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}


IndexPage.js



import React from 'react';

export default class IndexPage extends React.Component
{
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}

render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
};


app.js



import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './AppRoutes';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from './localStorage';
import throttle from 'lodash/throttle';
import { createStore, compose, applyMiddleware } from 'redux';
import RootReducer from './reducers/flightControlApp';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { getMuiTheme } from 'material-ui/styles';
import IndexPage from './components/IndexPage';

import ErrorHandler from './components/ErrorHandler';

const middlewares = ;
middlewares.push(thunkMiddleware);

console.log("Running in DEBUG: " + DEBUG);

if (DEBUG)
{
const { logger } = require(`redux-logger`);
middlewares.push(logger);
// tests
//
// require('./UniTests/Test');
}

const persistedState = loadState();

let store = compose(applyMiddleware(...middlewares)) (createStore) (
RootReducer,
persistedState
);

if (DEBUG)
{
if (persistedState != undefined)
{
console.log('Initial state loaded: ');
console.log(persistedState);
}
}

store.subscribe(throttle(()=> {
saveState(store.getState());
}, 1000));

window.onload = () =>
{
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<ErrorHandler>
<IndexPage></IndexPage>
</ErrorHandler>
</MuiThemeProvider>,
document.getElementById('app'));
}


UPDATE



When the exception is thrown the UI doesn't crash, I can still click the counter that increases on click, but in the console I see:



Console output










share|improve this question

























  • What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

    – Matt Way
    Nov 23 '18 at 22:13











  • Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

    – Keith
    Nov 23 '18 at 22:52
















0















I've tried to use error boundaries to handle errors in my app, but for some reason the componentDidCatch is not called when an error is thrown. I've simplified my app to the example from the react documentation, but it still doesn't work.



My react version is 16.6.3.



ErrorHandler.js



import React from 'react';

export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}

componentDidCatch(error, errorInfo) {
console.log('catch called')
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}

render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}


IndexPage.js



import React from 'react';

export default class IndexPage extends React.Component
{
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}

render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
};


app.js



import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './AppRoutes';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from './localStorage';
import throttle from 'lodash/throttle';
import { createStore, compose, applyMiddleware } from 'redux';
import RootReducer from './reducers/flightControlApp';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { getMuiTheme } from 'material-ui/styles';
import IndexPage from './components/IndexPage';

import ErrorHandler from './components/ErrorHandler';

const middlewares = ;
middlewares.push(thunkMiddleware);

console.log("Running in DEBUG: " + DEBUG);

if (DEBUG)
{
const { logger } = require(`redux-logger`);
middlewares.push(logger);
// tests
//
// require('./UniTests/Test');
}

const persistedState = loadState();

let store = compose(applyMiddleware(...middlewares)) (createStore) (
RootReducer,
persistedState
);

if (DEBUG)
{
if (persistedState != undefined)
{
console.log('Initial state loaded: ');
console.log(persistedState);
}
}

store.subscribe(throttle(()=> {
saveState(store.getState());
}, 1000));

window.onload = () =>
{
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<ErrorHandler>
<IndexPage></IndexPage>
</ErrorHandler>
</MuiThemeProvider>,
document.getElementById('app'));
}


UPDATE



When the exception is thrown the UI doesn't crash, I can still click the counter that increases on click, but in the console I see:



Console output










share|improve this question

























  • What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

    – Matt Way
    Nov 23 '18 at 22:13











  • Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

    – Keith
    Nov 23 '18 at 22:52














0












0








0








I've tried to use error boundaries to handle errors in my app, but for some reason the componentDidCatch is not called when an error is thrown. I've simplified my app to the example from the react documentation, but it still doesn't work.



My react version is 16.6.3.



ErrorHandler.js



import React from 'react';

export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}

componentDidCatch(error, errorInfo) {
console.log('catch called')
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}

render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}


IndexPage.js



import React from 'react';

export default class IndexPage extends React.Component
{
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}

render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
};


app.js



import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './AppRoutes';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from './localStorage';
import throttle from 'lodash/throttle';
import { createStore, compose, applyMiddleware } from 'redux';
import RootReducer from './reducers/flightControlApp';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { getMuiTheme } from 'material-ui/styles';
import IndexPage from './components/IndexPage';

import ErrorHandler from './components/ErrorHandler';

const middlewares = ;
middlewares.push(thunkMiddleware);

console.log("Running in DEBUG: " + DEBUG);

if (DEBUG)
{
const { logger } = require(`redux-logger`);
middlewares.push(logger);
// tests
//
// require('./UniTests/Test');
}

const persistedState = loadState();

let store = compose(applyMiddleware(...middlewares)) (createStore) (
RootReducer,
persistedState
);

if (DEBUG)
{
if (persistedState != undefined)
{
console.log('Initial state loaded: ');
console.log(persistedState);
}
}

store.subscribe(throttle(()=> {
saveState(store.getState());
}, 1000));

window.onload = () =>
{
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<ErrorHandler>
<IndexPage></IndexPage>
</ErrorHandler>
</MuiThemeProvider>,
document.getElementById('app'));
}


UPDATE



When the exception is thrown the UI doesn't crash, I can still click the counter that increases on click, but in the console I see:



Console output










share|improve this question
















I've tried to use error boundaries to handle errors in my app, but for some reason the componentDidCatch is not called when an error is thrown. I've simplified my app to the example from the react documentation, but it still doesn't work.



My react version is 16.6.3.



ErrorHandler.js



import React from 'react';

export default class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { error: null, errorInfo: null };
}

componentDidCatch(error, errorInfo) {
console.log('catch called')
// Catch errors in any components below and re-render with error message
this.setState({
error: error,
errorInfo: errorInfo
})
// You can also log error messages to an error reporting service here
}

render() {
if (this.state.errorInfo) {
// Error path
return (
<div>
<h2>Something went wrong.</h2>
<details style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
// Normally, just render children
return this.props.children;
}
}


IndexPage.js



import React from 'react';

export default class IndexPage extends React.Component
{
constructor(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}

handleClick() {
this.setState(({counter}) => ({
counter: counter + 1
}));
}

render() {
if (this.state.counter === 5) {
// Simulate a JS error
throw new Error('I crashed!');
}
return <h1 onClick={this.handleClick}>{this.state.counter}</h1>;
}
};


app.js



import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import AppRoutes from './AppRoutes';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { loadState, saveState } from './localStorage';
import throttle from 'lodash/throttle';
import { createStore, compose, applyMiddleware } from 'redux';
import RootReducer from './reducers/flightControlApp';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { getMuiTheme } from 'material-ui/styles';
import IndexPage from './components/IndexPage';

import ErrorHandler from './components/ErrorHandler';

const middlewares = ;
middlewares.push(thunkMiddleware);

console.log("Running in DEBUG: " + DEBUG);

if (DEBUG)
{
const { logger } = require(`redux-logger`);
middlewares.push(logger);
// tests
//
// require('./UniTests/Test');
}

const persistedState = loadState();

let store = compose(applyMiddleware(...middlewares)) (createStore) (
RootReducer,
persistedState
);

if (DEBUG)
{
if (persistedState != undefined)
{
console.log('Initial state loaded: ');
console.log(persistedState);
}
}

store.subscribe(throttle(()=> {
saveState(store.getState());
}, 1000));

window.onload = () =>
{
ReactDOM.render(
<MuiThemeProvider muiTheme={getMuiTheme()}>
<ErrorHandler>
<IndexPage></IndexPage>
</ErrorHandler>
</MuiThemeProvider>,
document.getElementById('app'));
}


UPDATE



When the exception is thrown the UI doesn't crash, I can still click the counter that increases on click, but in the console I see:



Console output







javascript reactjs error-handling






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 22:38







Pio

















asked Nov 23 '18 at 22:01









PioPio

2,54083566




2,54083566













  • What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

    – Matt Way
    Nov 23 '18 at 22:13











  • Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

    – Keith
    Nov 23 '18 at 22:52



















  • What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

    – Matt Way
    Nov 23 '18 at 22:13











  • Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

    – Keith
    Nov 23 '18 at 22:52

















What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

– Matt Way
Nov 23 '18 at 22:13





What happens when the exception is thrown? Is it swallowed (possibly by somewhere else)? Or does it crash your app?

– Matt Way
Nov 23 '18 at 22:13













Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

– Keith
Nov 23 '18 at 22:52





Seems to work with the codepen link they provided -> codepen.io/gaearon/pen/wqvxGa?editors=0010

– Keith
Nov 23 '18 at 22:52












0






active

oldest

votes











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453350%2fcomponentdidcatch-is-not-called-on-throw%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























0






active

oldest

votes








0






active

oldest

votes









active

oldest

votes






active

oldest

votes
















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53453350%2fcomponentdidcatch-is-not-called-on-throw%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Feedback on college project

Futebolista

Albești (Vaslui)