Response: error() static method
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since October 2017.
Note: This feature is available inWeb Workers.
Theerror() static method of theResponse interface returns a newResponse object associated with a network error.
This is mainly useful when writing service workers: it enables a service worker to send a response from afetch event handler that will cause thefetch() call in the main app code to reject the promise.
An error response has itstype set toerror.
In this article
Syntax
Response.error()Parameters
None.
Return value
AResponse object.
Examples
>Returning a network error from a service worker
Suppose a web app has a service worker, which contains the followingfetch event handler:
// service-worker.jsself.addEventListener("fetch", (event) => { const url = new URL(event.request.url); if (url.pathname === "/salamander.jpg") { event.respondWith(Response.error()); }});With this service worker, all fetch requests from the app will pass through the service worker to the network, except for requests to fetch "salamander.jpg", which will reject. This means that the following main thread code would throw an error, and thecatch handler will run.
// main.jsconst image = document.querySelector("#image");try { const response = await fetch("salamander.jpg"); const blob = await response.blob(); const objectURL = URL.createObjectURL(blob); image.src = objectURL;} catch (e) { console.error(e);}Specifications
| Specification |
|---|
| Fetch> # ref-for-dom-response-error①> |