5

I have Python Flask (v 1.0.0) backend that returns an http response with status 400 and a custom error message

return Response('My custom errror message', 400)

In my frontend I have an API call to the backend using Fetch API:

fetch(url, options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(error => console.log(error));

Since 400 is a BAD REQUEST, fetch goes straight to catch and all I have is TypeError: Failed to fetch message.

How can I get my custom error message in frontend instead of Failed to fetch message? It is visible in the DevTools, so I hope it should be available in fetch somehow?

enter image description hereenter image description here

3
  • have you tried accessing response code in then block? Commented Jan 27, 2019 at 11:22
  • it goes straight to .catch, I think because it is a 400 response and fetch treats it as an error instantly. Commented Jan 27, 2019 at 11:26
  • Try this github.com/github/fetch/issues/203#issuecomment-143347675 Commented Feb 4, 2020 at 9:52

2 Answers 2

2

It turns out it was nginx configuration issue. I was right when I said that fetch goes straight to .catch when the response is 400 but the reason was that the request was actually failing - I was seeing a CORS error in the console. After adding always parameter to my nginx configuration, there are no more CORS errors and I can access My custom error message inside .then and it no longer goes straight to .catch. More details here: nginx add headers when returning 400 codes

Sign up to request clarification or add additional context in comments.

Comments

0

Fetch won't throw an exception in case of status out of 200-299 range. You are trying to parse plain text ("My custom error message") as a json and that's the cause of exception. You have to check response.status before calling json()

2 Comments

tldr: call text() instead of json() for response.status === 400
even if I change my first .then to .then(response => console.log(response.status)) it goes straight to .catch - first .then isn't even executed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.