Martin Pilaszek
Martin Pilaszek

Reputation: 115

Avoid Next.js runtime error with axios exception in API route

I'm trying to make an API route in Next that send a request to my backend and saves the token in the cookies, but 4xx responses throw an Unhandled runtime error. Everything works fine, but I got this runtime error; I want to handle the error by myself instead of getting this:

Unhandled Runtime Error AxiosError: Request failed with status code 400

import { signIn } from '@/services/auth'
import { NextApiRequest, NextApiResponse } from 'next'

export default async function signInHandler (req: NextApiRequest, res: NextApiResponse) {
  const { userName, password } = req.body
  const response = await signIn({ userName, password }).catch(e => e.response)
  if (response.status === 200) {
    // save token in cookies
  }
  return res.status(response.status).json(response.data)
}
// signIn
export const signIn = ({ userName, password }: {userName: string, password: string}) =>
  api.post(`${baseEndpoint}/sign-in`, { userName, password })

// api
export const api = axios.create({
  baseURL: baseApiUrl,
  headers: {
    'Content-Type': 'application/json'
  }
})

Next runtime error

Upvotes: 1

Views: 1330

Answers (1)

Youssouf Oumar
Youssouf Oumar

Reputation: 45963

You could simply wrap your request with axios inside a try-catch. As an example like below:

import { signIn } from "@/services/auth";
import { NextApiRequest, NextApiResponse } from "next";

export default async function signInHandler(req: NextApiRequest, res: NextApiResponse) {
  const { userName, password } = req.body;
  try {
    const response = await signIn({ userName, password }).catch((e) => e.response);
    // save token in cookies
    return res.status(response.status).json(response.data);
  } catch (error) {
    // add the logic for when a sign-in fails here
    console.log(error);
  }
}

Upvotes: 1

Related Questions