我如何摆脱axios错误未捕获(在承诺中)



我在控制台中面临一个未捕获的错误,它的axios相关错误,我在这里粘贴了代码userSearch.jsx文件代码,其中错误显示在函数的最后一个括号的末尾?在函数最后一个括号的末尾,我得到了叉号,为什么?真正的错误是什么?

import { useState, useContext } from "react";
import GithubContext from "../../context/github/GithubContext";
import AlertContext from "../../context/alert/AlertContext";
import { searchUsers } from "../../context/github/GithubActions";
function UserSearch() {
const [text, setText] = useState('')
const { users, dispatch } = useContext(GithubContext)
const { setAlert } = useContext(AlertContext)
const handleChange = (e) => setText(e.target.value)
const handleSubmit = async (e) => {
e.preventDefault()
if (text === '') {
setAlert('Please enter something', 'error')
} else {
dispatch({ type: 'SET_LOADING' })
const users = await searchUsers(text)
dispatch({ type: 'GET_USERS', payload: users })
setText('')
}
}

return (
<div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
<div>
<form onSubmit={handleSubmit}>
<div className='form-control'>
<div className='relative'>
<input
type='text'
className='w-full pr-40 bg-gray-200 input input-lg text-black'
placeholder='Search'
value={text}
onChange={handleChange}
/>
<button
type='submit'
className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
>
Go
</button>
</div>
</div>
</form>
</div>
{users.length > 0 && (
<div>
<button
onClick={() => dispatch({ type: "CLEAR_USERS" })}
className='btn btn-ghost btn-lg'
>
Clear
</button>
</div>
)}
</div>
);
}
export default UserSearch;

在控制台中显示错误

GET https://api.github.com/search/users?q=brad 401
dispatchXhrRequest @ xhr.js:220
xhrAdapter @ xhr.js:16
dispatchRequest @ dispatchRequest.js:58
request @ Axios.js:109
Axios.<computed> @ Axios.js:131
wrap @ bind.js:9
searchUsers @ GithubActions.js:16
handleSubmit @ UserSearch.jsx:21
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430
UserSearch.jsx:26 //ITS ERROR SHOWING BY THE END OF FUCNTION'S LAST BRACKET, ITS SHOWING CROSS SIGN ERROR AT THE END OF OF BRACKET

Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
handleSubmit @ UserSearch.jsx:26
await in handleSubmit (async)
callCallback @ react-dom.development.js:4164
invokeGuardedCallbackDev @ react-dom.development.js:4213
invokeGuardedCallback @ react-dom.development.js:4277
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:4291
executeDispatch @ react-dom.development.js:9041
processDispatchQueueItemsInOrder @ react-dom.development.js:9073
processDispatchQueue @ react-dom.development.js:9086
dispatchEventsForPlugins @ react-dom.development.js:9097
(anonymous) @ react-dom.development.js:9288
batchedUpdates$1 @ react-dom.development.js:26140
batchedUpdates @ react-dom.development.js:3991
dispatchEventForPluginEventSystem @ react-dom.development.js:9287
dispatchEventWithEnableCapturePhaseSelectiveHydrationWithoutDiscreteEventReplay @ react-dom.development.js:6465
dispatchEvent @ react-dom.development.js:6457
dispatchDiscreteEvent @ react-dom.development.js:6430

GithubAction.js文件,其中添加了axios

import axios from 'axios'
const GITHUB_URL = process.env.REACT_APP_GITHUB_URL
const GITHUB_TOKEN = process.env.REACT_APP_GITHUB_TOKEN
const github = axios.create({
baseURL: GITHUB_URL,
headers: { Authorization: `token ${GITHUB_TOKEN}` },
})
// Get search results
export const searchUsers = async (text) => {
const params = new URLSearchParams({
q: text,
})
const response = await github.get(`/search/users?${params}`)
return response.data.items
}
// Get user and repos
export const getUserAndRepos = async (login) => {
const [user, repos] = await Promise.all([
github.get(`/users/${login}`),
github.get(`/users/${login}/repos`),
])
return { user: user.data, repos: repos.data }
}

您的错误控制台GET https://api.github.com/search/users?q=brad 401的第一行有错误代码401,这表明用户未经授权,因此GitHub拒绝了您的API请求。令牌可能不正确或已过期。

第二个错误与Axios、有关

Uncaught (in promise) AxiosError {message: 'Request failed with status code 401', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}

发生这种情况的原因是,对GitHub的API调用失败,返回401错误代码,并且您没有在代码中实现任何错误处理机制来正确捕获错误并进行处理。

UserSearch.jsx中,修改handleSubmit函数以使用try-catch块

const handleSubmit = async (e) => {
e.preventDefault();
try {
if (text === "") {
setAlert("Please enter something", "error");
} else {
dispatch({ type: "SET_LOADING" });
const users = await searchUsers(text);
dispatch({ type: "GET_USERS", payload: users });
setText("");
}
} catch (error) {
console.log(error.response.data.error)
}
}

发生这种情况是因为API对GitHub的调用失败,返回401错误代码中没有实现任何错误处理机制正确捕捉错误并处理主题的代码。

当我读到这个答案时,我也面临着同样的问题,我回去检查我的代码时意识到,当我在中返回一个值时

doSomething
.catch(error) { reject(false) }

我没有在调用方函数的catch块中接收到它作为

doSomethingCaller
.catch(error) { }

一旦您编写了一些错误处理代码,它就会停止显示错误。

最新更新