Merge pull request #2 from 0x1eef/handle_non_200_status

Handle a non-200 status code as an error
This commit is contained in:
0x1eef 2023-09-28 11:40:12 -03:00 committed by GitHub
commit df3334914f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -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));
}); });