React Router 6.22.3中如何在Loader中处理401错误并触发ErrorElement?
解决React Router Loader未捕获401错误的问题
问题核心:fetch API仅在网络层面出错时才会触发catch,像401这类HTTP错误状态码不会自动抛出异常,导致你的DashbaordLoader无法捕获错误,也就触发不了errorElement。
解决方案:修改fetcher函数,手动处理HTTP错误
在fetcher中检查响应的ok属性,若为false(即状态码不在200-299区间),则主动抛出包含错误信息和状态码的异常:
export const fetcher = async (url: string, method: string) => { const response = await fetch(url, { method, headers: { "Content-Type": "application/json", Authorization: "", }, }); // 检查响应状态,非成功状态主动抛错 if (!response.ok) { const errorData = await response.json(); const error = new Error(errorData.error || '请求失败'); // 给错误对象添加状态码属性,方便后续处理 (error as any).status = response.status; throw error; } return response.json(); };
为什么这样改?
- 当服务器返回401时,
response.ok会是false,此时我们解析响应体的错误信息,封装成Error对象抛出。 DashbaordLoader的catch块就能捕获到这个错误,进而触发React Router的errorElement渲染错误组件。
可选:在Error组件中获取错误详情
如果需要在Error组件里展示具体错误信息,可以用React Router提供的useRouteError()钩子:
import { useRouteError } from 'react-router-dom'; export default function Error() { const error = useRouteError() as Error & { status?: number }; return ( <div> <h1>出错了</h1> <p>{error.message}</p> {error.status && <p>状态码:{error.status}</p>} </div> ); }
内容的提问来源于stack exchange,提问作者Khant Min Si Thu
相关产品推荐
相关产品推荐

