admin管理员组文章数量:1302871
I'm using WordPress' apiFetch library to make requests (in WordPress admin dashboard) to my WordPress REST endpoints. It looks like apiFetch will throw an error if the response is a non-2xx code, using the JSON body of the response as the error. However, it does not appear to be inserting the HTTP code anywhere in that error.
This is necessary since it allows me to differentiate between a "normal" error (like 404 if the resource asked for does not exist) and an "unexpected" error (like a 500 internal server error).
I'm using WordPress' apiFetch library to make requests (in WordPress admin dashboard) to my WordPress REST endpoints. It looks like apiFetch will throw an error if the response is a non-2xx code, using the JSON body of the response as the error. However, it does not appear to be inserting the HTTP code anywhere in that error.
This is necessary since it allows me to differentiate between a "normal" error (like 404 if the resource asked for does not exist) and an "unexpected" error (like a 500 internal server error).
Share Improve this question asked Dec 18, 2020 at 7:04 Nicholas HarrisNicholas Harris 1085 bronze badges 2- It looks like it's still expecting a JSON response body in a failure case, which is what it returns instead. Maybe your API could return JSON in the normal error cases too? But I agree swallowing the status code is not useful. – Rup Commented Dec 18, 2020 at 10:27
- I'm catching all errors in the PHP endpoint and returning a JSON-formatted generic "Internal server error" message, so even unexpected errors would still be JSON. I could just check for the presence of an error key in the JSON object, but I'm trying to indicate the type of error as much as possible by HTTP codes rather than some sort of unique error string. – Nicholas Harris Commented Dec 18, 2020 at 18:50
1 Answer
Reset to default 3By default, apiFetch will parse the response for you automatically. You can get the raw response object by setting parse
to false
in the apiFetch
option, e.g.:
const handleClick = async () => {
try {
const result = await apiFetch( {
path: '/your/path',
parse: false,
} );
console.log( result ) // you will see ok status (e.g. 200) in here.
} catch ( error ) {
console.log( error ); // you will see error status (e.g. 404 or 500) in here.
}
};
More info: apiFetch's parse option
Relevant code for parsing the response: see utils/response.js in apiFetch
本文标签: javascriptGet HTTP response code on non2xx apiFetch request
版权声明:本文标题:javascript - Get HTTP response code on non-2xx apiFetch request 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741725104a2394581.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论