调用Salesforce POST接口时catch块处理AxiosError返回状态码误为200
根因分析
你的代码在axios的catch块中将错误响应体直接作为正常返回值返回,没有传递错误状态码,上层路由接口将这个返回值判定为正常响应,默认返回200状态码,和返回内容是否为错误信息无关。
修复方案
方法1:通过异常传递错误(推荐,适配多数后端框架的统一异常处理逻辑)
改造axios调用的catch块,不要吞掉错误,直接抛出携带状态码和错误信息的异常:
return axios({ url, method: 'post', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens.authentication}`, }, data: jsonData, timeout: 10000 }).then((response: AxiosResponse<any>) => { return response.data }).catch((error: AxiosError) => { console.log(error.response?.data); console.log(error.response?.status); console.log(error.response?.headers); // NestJS框架直接使用内置HttpException,原生Koa可以自定义异常类后续统一捕获 throw new HttpException( error.response?.data || '调用Salesforce接口异常', error.response?.status || 500 ) });
只要你的项目配置了全局异常拦截器,抛出的异常会自动被捕获,将响应状态码设置为你指定的状态码,错误信息作为响应体返回,无需修改上层路由代码。
方法2:手动传递状态码到上层路由设置
如果不想用异常处理,就改造axios返回结构,同时返回状态码和响应数据,再在上层路由手动设置状态码:
- 改造axios调用逻辑:
return axios({ url, method: 'post', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${tokens.authentication}`, }, data: jsonData, timeout: 10000 }).then((response: AxiosResponse<any>) => { return { status: response.status, data: response.data } }).catch((error: AxiosError) => { console.log(error.response?.data); console.log(error.response?.status); console.log(error.response?.headers); return { status: error.response?.status || 500, data: error.response?.data || {message: '调用Salesforce接口异常'} } });
- 改造上层路由逻辑,手动设置响应状态码:
@Post('case/businessContact') public async handleCreateBusinessContactCase( @Body() requestBody: ContactRequest, @Request() request: koa.Request, @Header('X-Correlation-Id') correlationId?: string, ): Promise<any> { const logCtx = LogContext.getLogContext(request.ctx, 'handleCreateBusinessContactCase'); const result = await createBusinessContactCase(logCtx, requestBody); // 手动设置koa响应状态码 request.ctx.status = result.status; return result.data; }
验证排查项
- 改造完成后触发Salesforce返回400的场景,直接调用接口查看响应头中的状态码是否符合预期
- 检查项目是否存在全局响应拦截器,确认没有逻辑强制将所有响应的状态码覆盖为200
- 确认Swagger配置没有强制绑定该接口的响应状态码为200,正常配置下Swagger会自动匹配接口实际返回的状态码
内容的提问来源于stack exchange,提问作者JonB
相关产品推荐
相关产品推荐

