Handling errors

  1. Let's adjust the URL in our request:
.get<IPost[]>("https://jsonplaceholder.typicode.com/postsX")

If we look at the running app, the posts are no longer being rendered.

  1. We want to handle this situation and give the user some feedback. We can do this using a catch method:
axios
.get<IPost[]>("https://jsonplaceholder.typicode.com/postsX")
.then( ... )
.catch(ex => {
const error =
ex.response.status === 404
? "Resource not found"
: "An unexpected error has occurred";
this.setState({ error });
});

So, unlike fetch, HTTP status error codes can be handled in the catch method. The error object argument in catch contains a response property containing information about the response, including the HTTP status code. 

  1. We just referenced a piece of state called error in the catch method. We'll use this in the next step to render the error message. However, we first need to add this state to our interface and initialize it:
interface IState {
posts: IPost[];
error: string;
}
class App extends React.Component<{}, IState> {
public constructor(props: {}) {
super(props);
this.state = {
posts: [],
error: ""
};
}
}
  1. Let's then render the error if it contains a value:
<ul className="posts">
...
</ul>
{this.state.error && <p className="error">{this.state.error}</p>}
  1. Let's add the error CSS class we just referenced to index.css:
.error {
color: red;
}

If we look at the running app now, we'll see Resource not found in red.

  1. Let's now change the URL to a valid URL so that we can move on to looking at how we can include HTTP headers in the next section:
.get<IPost[]>("https://jsonplaceholder.typicode.com/posts")

So, handling HTTP errors with axios is different than with fetch. We handle them in the first then method with fetch, whereas we handle them in the catch method with axios.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.105.108