user2086493
user2086493

Reputation: 31

Problem with catching exceptions from async code in ReactJs

I have following code inside react app (top level file - just to show the problem, i know its not the right place to do api calls and retrieve the data):

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

async function run() {
    try {
        return await fetch("https://somenonexistingplace.com"); 
    } catch (e) {
        console.error(e);
    } 
}

run();

ReactDOM.render(<App />, document.getElementById('root'));

When I run this code, catch obviously caches the exception but says 'e is undefined' - so I cannot access error message that normally lives in e. See screenshot from debug session

When I run such a code outside of React app in a plain script attached to html, everything works fine and e is an object with correct error message.

The only difference is that first example lives in React app and second one is outside of React.

So my questions is: what happens here and how to fix it?

EDIT: I know I can replace it with promises and .catch(...) but thats not the point - I am interested in why try/catch does not work here as expected.

Upvotes: 0

Views: 2206

Answers (4)

Harsh Mandalgi
Harsh Mandalgi

Reputation: 204

This works for me in node while using axios to fetch response from URL:

const axios = require("axios");

async function run() {
    try {
        return await axios.get("https://somenonexistingplace.com"); 
    } catch (e) {
        console.error(e);
    } 
}

Got the same problem where await was not working properly while using https module.

Upvotes: 0

ravibagul91
ravibagul91

Reputation: 20755

try / catch is great but it only works for imperative code.

From the docs,

Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.

Just example,

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }
    return this.props.children;
  }
}

Usage,

<ErrorBoundary>
  <YourComponent />
</ErrorBoundary>

Upvotes: 1

Josep Vidal
Josep Vidal

Reputation: 2661

I would recommend to change the syntaxis from try/catch to fetch().catch()

return await fetch("https://somenonexistingplace.com").catch(e => console.error(e))

Upvotes: 2

Nikhil Patil
Nikhil Patil

Reputation: 316

try this-->

URL='http://<--some wrong url -->'

async function run() {
        const resp= await fetch(URL);
        console.log(resp)

}

If any error appear it should appear in response it self.

Upvotes: 0

Related Questions