2021年5月3日星期一

General 400/500 error handling in reactjs

I have been building a react website and may need support in creating error pages 404, 500 but I am unsure how to get this working - as I have many api services/actions - how would the errorhandler be invoked if an error occurs in any or all services?

I've seen this link on handling granular error pages - https://code-maze.com/react-net-core-error-handling/

The error page I have in place is just a 404 if the routes fail to work with other pages - so its a the bottom of the routes.

so I've made the two pages

import NotFound from './components/ErrorPages/NotFound/NotFound';  import InternalServer from './components/ErrorPages/InternalServer/InternalServer';  

at the bottom of the route

        <Route exact path="/" render={() => (<Home/>)} />                    <Route path="/500" component={InternalServer} />          <Route path="*" component={NotFound} />        </Switch>  

//actions

export const HTTP_404_ERROR = 'HTTP_404_ERROR';  export const HTTP_500_ERROR = 'HTTP_500_ERROR';  export const HTTP_OTHER_ERROR = 'HTTP_OTHER_ERROR';      const execute404Handler = (props) => {      return {          type: HTTP_404_ERROR,          props: props      }  }  const execute500Handler = (props) => {      return {          type: HTTP_500_ERROR,          props: props      }  }  const executeOtherErrorHandler = (error) => {      return {          type: HTTP_OTHER_ERROR,          error: error      }  }  export const handleHTTPError = (error, props) => {      if (error.response.status === 404) {          return execute404Handler(props);      }      else if (error.response.status === 500) {          return execute500Handler(props);      }      else {          return executeOtherErrorHandler(error);      }  }  

//reducer

import { HTTP_404_ERROR, HTTP_500_ERROR, HTTP_OTHER_ERROR } from '../actions/errorHandlerActions';    const initialState = {      data: "",      showErrorModal: false,      errorMessage: ""  }  const execute404 = (state, action) => {      action.props.history.push('/404');      return { ...state, isError: true };  }  const execute500 = (state, action) => {      action.props.history.push('/500');      return { ...state, isError: true };  }  const executeOtherError = (state, action) => {      return {          ...state,          showErrorModal: true,          errorMessage: action.error.response.data      };  }    export function errorHandlerReducer (state = initialState, {type, payload} = {}) {    switch (type) {      case HTTP_404_ERROR:          return execute404(state, payload);      case HTTP_500_ERROR:          return execute500(state, payload);      case HTTP_OTHER_ERROR:          return executeOtherError(state, payload);            default:        return {...state}     }  }  

https://stackoverflow.com/questions/67314395/general-400-500-error-handling-in-reactjs April 29, 2021 at 05:12PM

没有评论:

发表评论