Get HTTP response code on non-2xx apiFetch request

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).

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

By 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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x