Home > Enterprise >  Is there a bettery way of Redirecting API Error on React.js
Is there a bettery way of Redirecting API Error on React.js

Time:11-22

I have an API which is .Net Core. I am trying to handle API post method errors. It is working but there will be a better way. And I can't write all status codes like that.

        .catch(function (err) {
          switch (err.response.status) {
            case 401:
              setRedirect(401)
            case 404:
              setRedirect(404)
            case 500:
              setRedirect(500)
            default:
              break
          }
        }

Too much if Statement. Is there a better way?

  if (redirect == 401) {
    return <Redirect to="/Login" />
  } else if (redirect == 404) {
    return <Redirect to="/404" />
  } else if (redirect == 500) {
    return <Redirect to="/500" />
  }
  return (
    <div>
      //...
    </div>
  )

CodePudding user response:

If you know statuses you can add them to array and check by includes.

.catch(err => {
  [401, 404, 500].includes(err.response.status) && setRedirect(err.response.status)
}

[401, 404, 500].includes(redirect) && (return <Redirect :to={redirect == 401 ? "/Login" : `/${redirect}` } />)
  • Related