Skip to content

Commit

Permalink
catching fetch errors (#4931)
Browse files Browse the repository at this point in the history
* catching fetch errors

* Update min.test.ts

---------

Co-authored-by: Harel M <[email protected]>
  • Loading branch information
jonathanlurie and HarelM authored Oct 30, 2024
1 parent 227cf70 commit d67fc04
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## main

### ✨ Features and improvements
- Catches network fetching errors such as CORS, DNS or malformed URL as actual `AJAXError` to expose HTTP request details to the `"error"` event (https://github.com/maplibre/maplibre-gl-js/pull/4822)
- _...Add new stuff here..._

### 🐞 Bug fixes
Expand Down
11 changes: 10 additions & 1 deletion src/util/ajax.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,16 @@ async function makeFetchRequest(requestParameters: RequestParameters, abortContr
request.headers.set('Accept', 'application/json');
}

const response = await fetch(request);
let response: Response;
try {
response = await fetch(request);
} catch (e) {
// When the error is due to CORS policy, DNS issue or malformed URL, the fetch call does not resolve but throws a generic TypeError instead.
// It is preferable to throw an AJAXError so that the Map event "error" can catch it and still have
// access to the faulty url. In such case, we provide the arbitrary HTTP error code of `0`.
throw new AJAXError(0, e.message, requestParameters.url, new Blob());
}

if (!response.ok) {
const body = await response.blob();
throw new AJAXError(response.status, response.statusText, requestParameters.url, body);
Expand Down
2 changes: 1 addition & 1 deletion test/build/min.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ describe('test min build', () => {
const decreaseQuota = 4096;

// feel free to update this value after you've checked that it has changed on purpose :-)
const expectedBytes = 889658;
const expectedBytes = 889777;

expect(actualBytes).toBeLessThan(expectedBytes + increaseQuota);
expect(actualBytes).toBeGreaterThan(expectedBytes - decreaseQuota);
Expand Down

0 comments on commit d67fc04

Please sign in to comment.