Handle a non-200 status code as an error

This commit is contained in:
0x1eef 2023-09-28 11:28:34 -03:00
parent 9d58e46b23
commit 83cd7416f5

View file

@ -8,9 +8,19 @@ export function useWebService(): [Maybe<TResponse>, Maybe<Error>] {
const [response, setResponse] = useState<Maybe<TResponse>>(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(() => {
fetch(endpoint)
.then((res) => res.json())
.then(receive)
.then((json) => setResponse(Response(json)))
.catch((err) => setError(err));
});