在保存传奇时没有出现异常

问题描述 投票:0回答:1

我正在做一个带有redux-saga状态管理的SPA。我的加载和保存方法本身是可以工作的,但是有很多奇怪的东西...... 下面是saga的代码。

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)
}
reactjs react-redux fetch redux-saga
1个回答
0
投票

使用@oozywaters的建议,我调整了代码。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.