alibaba / hooks

A high-quality & reliable React Hooks library. https://ahooks.pages.dev/
https://ahooks.js.org/
MIT License
13.91k stars 2.69k forks source link

[useRequest] onError param 获取 response payload #1074

Closed spondiirty closed 2 years ago

spondiirty commented 3 years ago

onError 只有两个参数,errorparam , error 现在只返回 http status 层的错误。 目前拿不到 payload, 是否可以把 data 也加到onError 里?

e.g.

api = useRequest(API.Login, {manual: true, onError: (error, param /*,data*/ ) => {
  log(error); //  400 Bad Request
  log(data); // ["the username cannot be empty"]
}} ;
api.run();
brickspert commented 3 years ago

error 是 API.Login Promise throw 出来的,useRequest 没做任何特殊处理。

可以单独看下 API.Login Promise throw error 是否符合要求。

spondiirty commented 3 years ago

API.Login 是我的url, Promise 指的是 useRequest 里面的 PromiseService 吗? 我直接在 run() 后面 catch 了, 是一样的,没有payload。

我找到了这个thread https://gist.github.com/odewahn/5a5eeb23279eed6a80d7798fdb47fe91 里面说的是要拿到payload, 得自己 throw 出来, 大概是这样

fetch(url)
    .then(res => {
        if (!res.ok) { return res.json().then(payload => { throw payload; }); }
        return res.json();
    })
    .catch(payload => {
        payload ...
    });

这个是用的fetch, 我看useAsync 里面没有 throw 语句,是不是umi-request 把它封起来了?

brickspert commented 2 years ago

Hello:

这个问题我们已经在 v3.0 版本彻底修复,目前 v3.0 版本已经发布 alpha 版本。

欢迎试用。

文档:https://ahooks-next.surge.sh/ 源码:https://github.com/alibaba/hooks/tree/next

安装最新分支

$ npm install --save ahooks@next
# or
$ yarn add ahooks@next

We have fixed this problem in the v3.0 version, and the alpha has been released.

Welcome to try.

Doc:https://ahooks-next.surge.sh/ Source Code:https://github.com/alibaba/hooks/tree/next

Install v3.0

$ npm install --save ahooks@next
# or
$ yarn add ahooks@next