禁止Chrome“无法加载资源”控制台中的消息

发布于 2024-10-08 19:07:57 字数 338 浏览 1 评论 0原文

我正在编写一个脚本,该脚本使用 XMLHttpRequest 来搜索由相对路径定义的文件,方法是尝试根据脚本识别的其他相同域绝对路径解析相对路径,然后尝试从解析的文件加载文件网址。如果遇到 404,我只是尝试根据另一个绝对路径解析文件相对路径,然后重试。对于这个特定的脚本,遇到 404 是完全可以的,但是,我的控制台上到处都是“无法加载资源:服务器以 404(未找到)状态消息进行响应,我想抑制它们”。

据我所知,没有任何错误需要捕获 - 错误情况由 xmlHttpRequest.onreadystatechange 处理程序处理,并且没有 window.onerror。

有什么办法可以抑制这些消息吗?

谢谢

I'm writing a script that uses an XMLHttpRequest to search for a file defined by a relative path, by attempting to resolve that relative path against other same domain absolute paths that the script is aware of, then attempting to load the file from that resolved url. If I encounter a 404, I just try to resolve the files relative path against another absolute path, and try again. For this particular script, its perfectly fine to encounter a 404- however, my console is littered with 'Failed to load resource: the server responded with a status of 404 (Not Found) messages, and I want to suppress them.

There is no error to catch as far as I can see- error cases are handled by the xmlHttpRequest.onreadystatechange handler, and there is no window.onerror.

Is there any way to suppress these messages?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

就此别过 2024-10-15 19:07:57

此功能于去年引入。您可以在此处启用它:DevTools->Settings->General->Console-> 隐藏网络消息

在 Chrome DevTools 中隐藏网络消息

另请参阅过滤控制台输出开发工具文档中的其他设置

This feature was introduced last year. You can enable it here: DevTools->Settings->General->Console->Hide network messages.

Hiding network messages in Chrome DevTools

See also Filtering the Console output and Additional settings in the devtools documentation.

十二 2024-10-15 19:07:57

唉,无论如何,如果状态代码是 4XX 或 5XX,浏览器都会在控制台中打印网络错误。可以按照 Doug 的回答建议的方式过滤错误,但这些错误仍然存​​在(即它们没有被抑制,只是被过滤),并且如果您再次取消选中该复选框,它们就会重新出现。

为了避免这些错误,最简单的解决方案是不要从服务器返回 4XX 响应,但这有点像政客那样撒谎和破坏协议。

客户端的干净解决方案可以通过以下步骤实现:

1. 注册一个服务工作线程来拦截后台请求

navigator.serviceWorker.register("noerr.js").then(_=> navigator.serviceWorker.controller
    ? window.dispatchEvent(new CustomEvent("swready")) // normal reload
    : navigator.serviceWorker.ready.then(_=> location.reload()) // first load or Ctrl+F5
);

自自定义 swready 事件以来抑制工作。

2. 替换 Service Worker 中的 4XX 和 5XX 响应

noerr.js Service Worker 可以这样编写:

self.addEventListener('install', e => {
    self.skipWaiting(); // update even if other tabs are open in the browser
});

const proxyResponse = orig => orig.status<400 ? orig : new Response(null, {
    status: 202,
    statusText: "Accepted",
    headers: new Headers({
        "Status": orig.status,
        "StatusText": orig.statusText
    })
});

self.addEventListener('fetch', e => e.respondWith(
    fetch(e.request).then(proxyResponse)
));

如果服务器响应 4XX 或 5XX,则软件拦截该请求并返回 202 已接受 状态代码而是根据标准:

202 Accepted响应状态码表示请求已被接受处理,但处理尚未完成;事实上,处理可能还没有开始。该请求最终可能会或可能不会被执行,因为在实际处理时可能会拒绝该请求。 202 是非承诺的,这意味着 HTTP 无法稍后发送异步响应来指示处理请求的结果。它适用于另一个进程或服务器处理请求或批处理的情况。

引用中提到的进程是我们的 ServiceWorker,它在 Status 标头中返回原始 HTTP 状态代码。

示例

window.addEventListener("swready", _=> {
    // suppressing network errors works since now
    fetch("nonexistent.html").then(r =>
        r.headers.get("Status")==404 && console.log("Server says 404")
        // no error appears in browser console
    )
});

现在,正确的方法不是 console.log,而是在响应被视为错误时抛出,并可选择稍后捕获它(未捕获的异常会引发控制台错误)。

无缝解决方案

为了实现这一点,我们可以编写一个 fetch2 函数,其作用类似于 fetch(),但不会在 4XX 和 5XX 上写入控制台错误:

const fetch2 = (req, opt) => fetch(req, opt).then(res =>
    res.status!=202 ? res : new Response(null, {
        status: res.headers.get("Status"),
        statusText: res.headers.get("StatusText"),
        headers: res.headers
    })
);

// receives the response body or false if not ok
// called on any response including 4XX or 5XX
function responseHandler(body) { ... }

// called when the server does not respond
// or if the responseHandler throws
function serverError(errorEvent) { ... }

// never generates console.error
fetch2("nonexistent.html")
.then(r => r.ok && r.text())
.then(responseHandler)
.catch(serverError)

window.onerror

为了澄清您的问题,有 window.onerror。当响应代码为 4XX 或 5XX 时,不会触发它,因为它仍然是有效响应,而不是错误。仅当服务器没有响应时才会引发错误。

console.clear

console.clear() 不是正确的方法,因为它清除所有控制台注释,而不仅仅是网络错误。在我的用例中,我想每分钟对服务器执行一次 ping 操作,以检查它当前是否可用。调试它是一项艰巨的任务:从 ping 中浏览数千个控制台错误并查找真正的错误。

Alas, the browsers print network error in the console if the status code is 4XX or 5XX no matter what. It is possible to filter the errors as Doug's answer suggests, but those errors are still there (i.e. they are not suppressed, just filtered) and they reappear if you uncheck the checkbox again.

To avoid those errors, the simplest solution is not to return 4XX responses from the server, but this is kind of lying and breaking the protocol like politicians do.

The clean solution on the client side can be achieved with these steps:

1. Register a service worker to intercept background requests

navigator.serviceWorker.register("noerr.js").then(_=> navigator.serviceWorker.controller
    ? window.dispatchEvent(new CustomEvent("swready")) // normal reload
    : navigator.serviceWorker.ready.then(_=> location.reload()) // first load or Ctrl+F5
);

Suppressing works since the custom swready event.

2. Replace the 4XX and 5XX responses in the service worker

The noerr.js service worker could be written like this:

self.addEventListener('install', e => {
    self.skipWaiting(); // update even if other tabs are open in the browser
});

const proxyResponse = orig => orig.status<400 ? orig : new Response(null, {
    status: 202,
    statusText: "Accepted",
    headers: new Headers({
        "Status": orig.status,
        "StatusText": orig.statusText
    })
});

self.addEventListener('fetch', e => e.respondWith(
    fetch(e.request).then(proxyResponse)
));

If the server responds 4XX or 5XX, the SW intercepts the request and returns 202 Accepted status code instead in accordance to the standard:

202 Accepted response status code indicates that the request has been accepted for processing, but the processing has not been completed; in fact, processing may not have started yet. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. 202 is non-committal, meaning that there is no way for the HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing.

The process mentioned in the quote is our ServiceWorker which returns the original HTTP status code in the Status header.

Example

window.addEventListener("swready", _=> {
    // suppressing network errors works since now
    fetch("nonexistent.html").then(r =>
        r.headers.get("Status")==404 && console.log("Server says 404")
        // no error appears in browser console
    )
});

Now instead of console.log, the correct approach is to throw in case when the response is considered errorneous, and optionally catch it later (uncaught exceptions promote to console error).

Seamless solution

To achieve this, we can write a fetch2 function that acts like fetch(), but doesn't write console errors on 4XX and 5XX:

const fetch2 = (req, opt) => fetch(req, opt).then(res =>
    res.status!=202 ? res : new Response(null, {
        status: res.headers.get("Status"),
        statusText: res.headers.get("StatusText"),
        headers: res.headers
    })
);

// receives the response body or false if not ok
// called on any response including 4XX or 5XX
function responseHandler(body) { ... }

// called when the server does not respond
// or if the responseHandler throws
function serverError(errorEvent) { ... }

// never generates console.error
fetch2("nonexistent.html")
.then(r => r.ok && r.text())
.then(responseHandler)
.catch(serverError)

window.onerror

To clarify your question, there is window.onerror. It is not fired when the response code is 4XX or 5XX, since it is still a valid response, not error. Error is fired only if the server doesn't respond.

console.clear

console.clear() is not the right approach, since it clears all the console notes, not just network errors. In my use case, I wanted to ping the server every minute to check if it is currently available. It was daunting to debug it: to browse through thousands of console errors from the ping and look for real errors.

七色彩虹 2024-10-15 19:07:57

catch 块或错误处理函数中使用 console.clear()
记录后,它将立即清除控制台上的这些请求错误。

请注意

来自 MDN

请注意,在 Google Chrome 中,如果用户在设置中选择了“在导航时保留日志”,则 console.clear() 不起作用。

在 MDN 上了解更多相关信息

try {
  var req = new XMLHttpRequest();
  req.open('GET', 'https://invalidurl', false);
  req.send();
} catch(e) {
  console.clear();
}

应该记录这个

获取 https://invalidurl/ net::ERR_NAME_NOT_RESOLVED

但它将被清除。

Use console.clear() in the catch block or error handler function.
It will clear those request error on the console immediately after it is logged.

PLEASE NOTE

From MDN

Note that in Google Chrome, console.clear() has no effect if the user has selected "Preserve log upon navigation" in the settings.

Read more about it on MDN

try {
  var req = new XMLHttpRequest();
  req.open('GET', 'https://invalidurl', false);
  req.send();
} catch(e) {
  console.clear();
}

Should log this

GET https://invalidurl/ net::ERR_NAME_NOT_RESOLVED

but it will be cleared.

羁绊已千年 2024-10-15 19:07:57

对于 2023 年仍在寻找此问题答案的人,控制台选项卡中的设置下有一个“隐藏网络”复选框。在此处输入图像描述

For anyone still looking for an answer to this in 2023, there's a checkbox for "hide network" under settings in the console tab.enter image description here

极致的悲 2024-10-15 19:07:57

如果您使用 Web Worker 执行 XMLHttpRequest 请求,错误将被记录到工作脚本上下文中,因此它们不会出现在控制台上,除非专门选择此上下文进行显示。

If you use a web worker to perform XMLHttpRequest requests, the errors will be logged into the worker script context so they will not appear on the console unless this context will be specifically chosen for display.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文