Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. Web APIs
  3. Response
  4. error()

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.

Syntax

js
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:

js
// 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.

js
// 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①

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp