add error handling

This commit is contained in:
Maren Süwer
2018-10-25 14:24:53 +02:00
parent 36f289a153
commit cab29ba509

View File

@@ -31,7 +31,9 @@ type Props = {
}; };
type State = { type State = {
contentType: string contentType: string,
error: Error,
hasError: boolean
}; };
class Content extends React.Component<Props, State> { class Content extends React.Component<Props, State> {
@@ -39,25 +41,44 @@ class Content extends React.Component<Props, State> {
super(props); super(props);
this.state = { this.state = {
contentType: "" contentType: "",
error: new Error(),
hasError: false
}; };
} }
componentDidMount() { componentDidMount() {
const { file } = this.props; const { file } = this.props;
getContentType(file._links.self.href).then(result => { getContentType(file._links.self.href)
this.setState({ .then(result => {
contentType: result if (result.error) {
}); this.setState({
}); ...this.state,
hasError: true,
error: result.error
});
} else {
this.setState({
...this.state,
contentType: result.type
});
}
})
.catch(err => {});
} }
render() { render() {
const { file } = this.props; const { file } = this.props;
const contentType = this.state.contentType; const contentType = this.state.contentType;
const error = this.state.error;
const hasError = this.state.hasError;
if (!file) { if (!file) {
return <Loading />; return <Loading />;
} }
if (hasError) {
return <ErrorNotification error={error} />;
}
if (contentType.startsWith("image")) { if (contentType.startsWith("image")) {
return <ImageViewer />; return <ImageViewer />;
} }
@@ -74,10 +95,10 @@ export function getContentType(url: string, state: any) {
return apiClient return apiClient
.head(url) .head(url)
.then(response => { .then(response => {
return response.headers.get("Content-Type"); return { type: response.headers.get("Content-Type") };
}) })
.catch(err => { .catch(err => {
return null; return { error: err };
}); });
} }