Handle a non-200 status code as an error
This commit is contained in:
parent
9d58e46b23
commit
83cd7416f5
1 changed files with 11 additions and 1 deletions
|
@ -8,9 +8,19 @@ export function useWebService(): [Maybe<TResponse>, Maybe<Error>] {
|
||||||
const [response, setResponse] = useState<Maybe<TResponse>>(null);
|
const [response, setResponse] = useState<Maybe<TResponse>>(null);
|
||||||
const [error, setError] = useState<Maybe<Error>>(null);
|
const [error, setError] = useState<Maybe<Error>>(null);
|
||||||
|
|
||||||
|
function receive(res: Response) {
|
||||||
|
if (res.status === 200) {
|
||||||
|
return res.json();
|
||||||
|
} else {
|
||||||
|
const message = "There was an unexpected response from the web service. " +
|
||||||
|
`The status code was ${res.status}`;
|
||||||
|
throw new Error(message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetch(endpoint)
|
fetch(endpoint)
|
||||||
.then((res) => res.json())
|
.then(receive)
|
||||||
.then((json) => setResponse(Response(json)))
|
.then((json) => setResponse(Response(json)))
|
||||||
.catch((err) => setError(err));
|
.catch((err) => setError(err));
|
||||||
});
|
});
|
||||||
|
|
Loading…
Reference in a new issue