Asp.net core mvc 如何从fetch api获取实际错误

Asp.net core mvc 如何从fetch api获取实际错误,asp.net-core-mvc,fetch-api,Asp.net Core Mvc,Fetch Api,我正在进行fetch api调用,但如果出现500错误,以下中间件将启动并在响应体中发回一个json对象 app.Use(async (context, next) => { try { await next(); } catch (Exception ex) { if (context.Re

我正在进行fetch 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 */)
对象的函数返回一个承诺,而不是实际解析的值

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

谢谢你的帮助,现在可以用了。我已经更新了工作代码,但我觉得可以进一步重构。有什么建议吗?我认为你提出的解决方案不错。还有其他选择(例如),但我喜欢你的。我可以用一些lambda来缩短这个,再次感谢!!