Merge pull request #2 from 0x1eef/handle_non_200_status
Handle a non-200 status code as an error
This commit is contained in:
commit
df3334914f
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