保存传奇未引发异常

时间:2020-05-10 12:18:48

标签: reactjs react-redux fetch redux-saga

我正在使用带有redux-saga状态管理的SPA。我的加载和保存方法本身正在工作,但是有很多奇怪的东西……下面是传奇代码:

export function* getEventDetails({ id }) {
  const requestURL = `${url}/admin/event/${id}`
  try {
    const event = yield call(request, requestURL)
    yield put(eventLoaded(event, id))
  } catch (err) {
    yield put(eventLoadingError(err))
  }
}

export function* saveEventDetails({ event }) {
  const id = event['id']
  const requestURL = `${url}/admin/event/${
    !isNaN(id) && id !== undefined && id !== null ? id : 'new'
  }`
  try {
    const createdEvent = yield call(request, requestURL, {
      method: !isNaN(id) && id !== undefined && id !== null ? 'PUT' : 'POST',
      body: JSON.stringify(event)
    })
    yield put(eventSaved(createdEvent, createdEvent['id']))
    yield put(loadEvent(createdEvent['id']))
    yield put(loadPreviousEvents())
    yield put(loadUpcomingEvents())
  } catch (err) {
    console.log('caught error inside saga')
    yield put(eventSavingError(err))
  }
}

export default function* eventsData() {
  yield takeLatest(LOAD_EVENT, getEventDetails)
  yield takeLatest(SAVE_EVENT, saveEventDetails)
}

一件事情绝对是奇怪的-如果我关闭API服务器然后尝试保存,则在控制台中将永远看不到caught error inside saga。因此,我无法调度eventSavingError操作,等等。

我的错误动作在哪里?在控制台中,我看到:

reducer.js:48 action: {type: "project/Container/SAVE_EVENT", event: {…}}
request.js:55 PUT http://localhost:5000/event/10 net::ERR_CONNECTION_REFUSED

请求功能:

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response
  }
  const error = new Error(response.statusText)
  error.response = response
  throw error
}

export default function request(url, options) {
  const headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Access-Control-Request-Headers': 'Content-Type, Authorization'
  }
  const token = localStorage.getItem('token')
  if (token) {
    headers['Authorization'] = `Bearer ${token}`
  }
  const newOptions = {
    ...options,
    mode: 'cors',
    headers
  }
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
}

1 个答案:

答案 0 :(得分:0)

使用@oozywaters建议,我将代码调整为:

  return fetch(url, newOptions)
    .then(checkStatus)
    .then(parseJSON)
    .catch(err => {
      throw err
    })

它确实解决了缺少异常的问题。