Try-catch 对 JS 中的 400 错误不起作用

mah*_*hdi 1 javascript try-catch reactjs

这让我很紧张,我已经检查了几个小时的代码,但没有发现问题。在下面的代码中,我在正文中使用了一个无效的对象,以获得 400 错误(错误请求),因此在 catch 块中捕获它:

  <button onClick={() => {
    try {
      axiosInstance.post('/cart', { field: "invalid field" });
    } catch (err) {
      console.log("here!!!"); 
      console.error(err);
    }
  }}
  />
Run Code Online (Sandbox Code Playgroud)

我可以在网络选项卡中看到请求失败,在控制台中我可以看到:

POST http://api.[REDACTED]/api/cart 400 (Bad Request)
index.js:1375 Error: Request failed with status code 400
    at createError (createError.js:17)
    at settle (settle.js:19)
    at XMLHttpRequest.handleLoad (xhr.js:60)
Run Code Online (Sandbox Code Playgroud)

Tra*_*mes 6

axios http 请求是异步的,需要使用Promisesasync/await。试试这个,你会看到错误响应:

<button onClick={async () => {
    try {
      const response = await axiosInstance.post('/cart', { field: "invalid field" });
    } catch (err) {
      console.log("here!!!"); 
      console.error(err);
      console.error(err.response);
    }
  }}
  />
Run Code Online (Sandbox Code Playgroud)