Search code examples
javascriptaxioses6-promise

Catching 4xx and code errors separately with axios using then / catch syntax


I have been reading up on Promises and the then/catch syntax.

This article was very comprehensive and I thought I understood:

fetch()
  .then()
  .catch()

Here, catch() deals with errors which get thrown in code called within then().

var p = fetch()
p.then()
p.catch()

This would properly catch errors thrown by fetch() and process the correct response of fetch() within then().

Why is the behavior different in axios?

Here all examples I found use the first method to catch errors thrown by an axios() call. The result is that in

axios(/* axios stuff */)
  .then(successCallback)
  .catch(errorCallback)

errorCallback handles 4xx errors thrown by axios() but also any runtime errors thrown by successCallback. Or am I missing something here? Is there a way to separate these two classes of errors?


Solution

  • Promise link is like water flow. The last catch will catch all errors thrown before it if there's no handler in any front then's second argument

    If you don't want errorCallback to handle errors thrown by successCallback, you should put errorCallback to then's second argument.

    axios(/* axios stuff */)
      .then(successCallback, errorCallback)