我正在进行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))
遵循正确答案后的工作代码
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 */)