我有记录错误的记录功能。当Ajax请求以非JSON
数据类型失败时,log
方法应该记录它,但是,我们收到了变异的错误,如附带的屏幕截图所示。我想在log
内调用此service
操作。
代码
...
import {log} from '../actions/LoggingActions';
...
export default function request(url, opts, dispatch, type = 'application/x-www-form-urlencoded') {
...
return new Promise((resolve, reject) => {
$.ajax(args).then((data) => {
dispatch(httpEndRequest([url, opts, dispatch]));
resolve(data);
}).fail((jqXHR, textStatus, errorThrown) => {
const error = (jqXHR && jqXHR.responseJSON) ?
jqXHR.responseJSON.message :
'Error Making Request';
dispatch(httpFailRequest([url, opts, dispatch], error));
try {
reject(JSON.parse(jqXHR.responseText));
} catch (e) {
console.log(jqXHR.responseText, jqXHR, error);
reject(error);
dispatch(log('Received data is not in JSON format', {requestUrl: url}, {result: e, response: jqXHR, status: textStatus, error: errorThrown}, 'error'));
}
});
});
}
答案 0 :(得分:3)
不使用带有React的jQuery,而是使用axios或fetch(基于Promise的HTTP客户端)。我个人更喜欢axios。
要使用axios,请执行此操作
npm install axios --save
。然后
import axios from 'axios';
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
})
.then((response) => {
resolve(response.data);
})
.catch((error) => {
// error.response.status
dispatch(log(error));
reject(error);
});
});