diff --git a/CHANGELOG.md b/CHANGELOG.md index ed79148658..2646a4d8ef 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/src/util/ajax.ts b/src/util/ajax.ts index 3ac99989db..730dc63385 100644 --- a/src/util/ajax.ts +++ b/src/util/ajax.ts @@ -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); diff --git a/test/build/min.test.ts b/test/build/min.test.ts index 4f8c99fac3..712295c7c4 100644 --- a/test/build/min.test.ts +++ b/test/build/min.test.ts @@ -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);