【问题标题】:How to display server side validation errors with onFailure() in Edit/Create components?如何在编辑/创建组件中使用 onFailure() 显示服务器端验证错误?
【发布时间】:2021-12-23 02:12:38
【问题描述】:

我想在通知中显示服务器错误。默认情况下,当返回 400 时,通知会显示“错误请求”。 我试图用onFailure (https://marmelab.com/react-admin/CreateEdit.html#onfailure) 来改变行为,但是error 的参数似乎总是一个通用的HttpError()。消息不知何故丢失了。


export const MyEdit = (props) => {
  const refresh = useRefresh();

  const onFailure = (error) => {
    console.log('ERROR stack trace', error);  // show 'Error'
    console.log('ERROR stack trace', error.stack);  // show 'Error'
    refresh();
  };


  return (
    <Edit
      onFailure={onFailure}
      {...props}
    >
      <SimpleForm>
        <TextInput
          source="full_name"
          fullWidth
        />
        <TextInput
          source="email"
          fullWidth
        />
      </SimpleForm>
    </Edit>
  );
};

服务器端的响应通常是这样的

{
  field: [
    error_message_1,
    error_message_2,
    ...,
    error_message_n
  ]
}

用Chrome调试器,看来我的问题应该出在这个类上:


var HttpError = /** @class */ (function (_super) {
    __extends(HttpError, _super);
    function HttpError(message, status, body) {
        if (body === void 0) { body = null; }
        var _this = _super.call(this, message) || this;
        _this.message = message;
        _this.status = status;
        _this.body = body;
        Object.setPrototypeOf(_this, HttpError.prototype);
        _this.name = _this.constructor.name;
        if (typeof Error.captureStackTrace === 'function') {
            // Enter here
            Error.captureStackTrace(_this, _this.constructor);
        }
        else {
            _this.stack = new Error(message).stack;
        }
        // Returns an empty Error();
        _this.stack = new Error().stack;
        return _this;
    }
    return HttpError;
}(Error));

它返回一个空的 Error() 并且堆栈不包含以前的 messagebodystatus 的值。

那么我怎样才能显示服务器消息呢?任何帮助将不胜感激。

以防万一: 铬 95: 反应管理员:3.19

【问题讨论】:

    标签: javascript django-rest-framework react-admin


    【解决方案1】:

    找到答案了。

    我尝试了errorerror.messageerror.stack,但我没有尝试error.body。重新阅读我的问题后变得很明显。

    error.body 确实返回后端 JSON 响应。

    【讨论】:

    • 我打算删除我的问题,但我决定保留它以防其他人搜索相同的内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-07-08
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多