如何在React-admin中处理服务器错误?

时间:2019-04-04 05:51:49

标签: reactjs react-admin

我使用GraphQL-Yoga作为后端。
它返回的错误的格​​式与文档不匹配。但是我需要他们的翻译。在expected <- tibble(A=c('red','red','red','blue','blue','blue'), B=c('yes','no','no','no','no','no'), yes_in_group=c(TRUE, TRUE, TRUE, FALSE, FALSE, FALSE)) actual <- tibble(A=c('red','red','red','blue','blue','blue'), B=c('yes','no','no','no','no','no'), yes_in_group=c(TRUE, FALSE, FALSE, FALSE, FALSE, FALSE)) 中是否有一个地方可以捕获服务器中的所有错误,并按Notification组件的预期进行处理?

React -admin

2 个答案:

答案 0 :(得分:2)

我遇到了环回问题,因为它在错误对象内部而不是直接在响应的message属性中发送错误。我所做的是:

创建自己的httpClient,如用于设置身份验证令牌的文档中所述。

const httpClient = (url, options = {}) => {
    // ...
    return fetchUtils.fetchJson(url, options);
}
const dataProvider = jsonServerProvider('http://localhost:3000/api', httpClient);

在您的管理组件中:

<Admin dataProvider={dataProvider}>

然后,您需要创建自己的fetchJson实现:

import { HttpError } from 'react-admin';

const fetchJson = async (url, options = {}) => {
    const requestHeaders = (options.headers ||
        new Headers({
            Accept: 'application/json',
        })
    );
    if (!requestHeaders.has('Content-Type') &&
        !(options && options.body && options.body instanceof FormData)) {
        requestHeaders.set('Content-Type', 'application/json');
    }
    if (options.user && options.user.authenticated && options.user.token) {
        requestHeaders.set('Authorization', options.user.token);
    }
    const response = await fetch(url, { ...options, headers: requestHeaders })
    const text = await response.text()
    const o = {
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        body: text,
    };
    let status = o.status, statusText = o.statusText, headers = o.headers, body = o.body;
    let json;
    try {
        json = JSON.parse(body);
    } catch (e) {
        // not json, no big deal
    }
    if (status < 200 || status >= 300) {
        return Promise.reject(new HttpError((json && json.error && json.error.message) || statusText, status, json));
    }
    return Promise.resolve({ status: status, headers: headers, body: body, json: json });
};

这实际上只是fetchUtils.fetchJson的副本,但请注意:

return Promise.reject(new HttpError((json && json.error && json.error.message) || statusText, status, json));

这是您应该在json响应中设置错误消息的地方。

最后,您只需将fetchUtils.fetchJson更改为您的fetchJson方法:

const httpClient = (url, options = {}) => {
    // ...
    return fetchJson(url, options); // <--- change this line
}

答案 1 :(得分:0)

我的问题是,我没有在DataProvider中正确抛出错误,这是我如何通过react-admin显示HTTP错误:

import { GET_LIST } from "react-admin";

async function providerApi(type, resourceName, params) {
  let res;
  try {
    switch (type) {
      case GET_LIST:
        res = await MyGetList(resourceName, params);
        break;
      /* All other methods */
    }
    return res;
  } catch (error) {
    const errorMsg = error.toString();
    const code = translateErrorMessageToCode(errorMsg);
    const errorObj = { status: code, message: errorMsg, json: res };
    throw errorObj;
  }
}

function translateErrorMessageToCode(errorMsg) {
  if (errorMsg.includes('unauthenticated')) {
    return 401
  }
  if (errorMsg.includes('aborted')) {
    return 409
  }
  if (errorMsg.includes('not-found')) {
    return 404
  }
  return 200
}