如何从 fetch api 中获取实际错误

How can I get the actual error from fetch api

我正在进行提取 api 调用,但如果出现 500 错误,以下中间件会启动并在响应正文中发回 json 对象。

app.Use(async (context, next) =>
        {
            try
            {
                await next();
            }
            catch (Exception ex)
            {
                if (context.Response.HasStarted)
                {
                    throw;
                }
                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json";
                var json = JToken.FromObject(ex);
                await context.Response.WriteAsync(json.ToString());
            }
        });

在客户端我有以下代码

 return fetch(url, content)
    .then(function(res) {
        if (!res.ok) {
            console.log(res, res.json())
            throw Error(res.statusText);
          }
        return res;
      })
    .then(res => res.json())
    .catch(e => console.log('Error fetching accounts:', e))

我无法访问带有错误信息的 json。我该怎么做?

遵循正确答案后的工作代码

return fetch(url, content)
       .then(function(response) {
           if (!response.ok) {
              return response.json()
                   .then(function(obj) {
                       throw Error(obj.ErrorMessage)
                   })
           } 
           else {
              return response.json()
                               .then(json => {
                                   /*further processing */
                               })
           }
       }).catch(/* work with the error */)

json function of the Response 对象 returns 一个 Promise,而不是实际解析的值。

res.json()
.then(function(object) {
  // Here you have the parsed JSON object.
  console.log(object);
});