0

I am using nextjs api/routes I have a login and when an issue occurs return a 401 and message text that I would like to show to users.

A minimal example is:

Api : /api/v1/auth/sigin.js

export default async (req, res) => {
const { name, password } = req.body;
const url = process.env.SH_API_BASEURL + 'auth/signin';
console.log(url);

try {
    const resp = await axios.patch(url, { name, password });
    return res.status(200).send(resp.data);
} catch (err) {
    const { response } = err;
    const status = response.status;
    const message = response.data.errors[0].message;
    console.log(`status: ${status}, message ${message}`);
    return res.status(status).send(message);
}
};

Pages /pages/auth/signin.js

const handleFormSubmit = async (formData, e) => {
    e.preventDefault();
    try {
        const res = await axios.post('/api/v1/auth/signin', formData);
        

        router.push('/secure/home');
    } catch (err) {
        console.log('pages auth in error');
        console.log(err);
        setSubmitError(true);
        console.log('sigin handle submit error');
        
    }
};

console.log(err) shows the output

Error: Request failed with status code 401
at createError (createError.js:16)
at settle (settle.js:17)
at XMLHttpRequest.handleLoad (xhr.js:62)

How do I get access to the statusCode and text in pages code?

Could any answers be in the context of nextjs api/routes

Thanks

  • 1
    Does this: https://stackoverflow.com/questions/44806333/unable-to-catch-and-log-the-error-response-from-an-axios-request answer your question? – FrankPl Apr 21 '21 at 22:34
  • Does this answer your question? [How can I get the status code from an http error in Axios?](https://stackoverflow.com/questions/39153080/how-can-i-get-the-status-code-from-an-http-error-in-axios) – Danila Apr 21 '21 at 22:41

1 Answers1

0

You can access the response property of the axios error to get the status

const handleFormSubmit = async (formData, e) => {
    e.preventDefault();
    try {
        const res = await axios.post('/api/v1/auth/signin', formData);
        router.push('/secure/home');
    } catch (err) {
        console.log(err.response.status);
    }
};