You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Postman返回预期400响应,但Axios未抛异常且then返回undefined

问题:Unit SDK调用400响应未触发异常反而返回undefined

背景

正在使用Unit公司的SDK调用「创建交易对手」接口,该SDK底层基于Axios实现。预期请求返回400响应时,Axios客户端应抛出异常,但实际进入then回调并返回undefined。

自定义Axios实例配置

我们通过注入自定义Axios实例实现统一日志方案,代码如下:

import { crossAdapter } from './axios-adaptor';
import Axios, { AxiosInstance, AxiosResponse } from 'axios';
import { Logger } from '../context';

export type AxiosInstanceOpts = {
  logger?: Logger;
  validateStatus?: ((status: number) => boolean) | null | undefined;
};

export const getAxiosInstance = (opts?: AxiosInstanceOpts) => {
  const axios = Axios.create({
    adapter: crossAdapter() as any,
    transitional: {
      clarifyTimeoutError: true,
    },
    validateStatus: opts?.validateStatus,
  });

  if (opts?.logger) {
    const logger = opts.logger;
    axios.interceptors.response.use(
      (response: AxiosResponse) => {
        logger.info(
          {
            status: response.status,
            method: response.config?.method?.toUpperCase(),
            url: response.config?.url,
          },
          'Axios Response'
        );
        logger.debug(
          {
            body: response.data,
          },
          'Axios Response Body'
        );
        return response;
      },
      (error) => {
        logger.error(
          {
            err: error,
          },
          'Axios Response Error'
        );
      }
    );
  }

  return axios;
};

export type { AxiosInstance };

依赖注入与Unit Client初始化

通过懒加载包装类提供Unit Client:

export class ClientsImpl {

  _unitClient: Unit;

  get unitClient(): Unit {
    if (!this._unitClient) {
      const unitToken = (this._headers.get('Bank-Authorization') || '').replace(
        'Bearer ',
        ''
      );
      const unitUrl = this._config.unitUrl;
      if (!unitToken) {
        throw new Error('Unit Client not available for this request');
      }

      this._unitClient = getUnitClient(unitToken, unitUrl, {
        validateStatus(status) {
          return status < 300;
        },
        logger: this._logger,
      });
    }

    return this._unitClient;
  }
}

服务调用代码

class CounterpartyService {
   async createVerifiedCounterparty(
    userId: string,
    customerId: string,
    input: VerifiedCounterpartyInput
  ): Promise<
    Result<AchCounterparty, UnitError | UnitHttpError | UnexpectedError>
  > {
    const logger = this.context.logger;
    try {
      const { uuid } = this.context.utils;
      const { unitClient} = this.context.clients;

      const result = await unitClient.counterparties
        .create({
          type: 'achCounterparty',
          attributes,
          relationships: {
            customer: {
              data: {
                type: 'customer',
                id: customerId,
              },
            },
          },
        })
        .then((response) => Ok(response.data))
        .catch((error: any) => {
          if (error.response) {
            // The request was made and the server responded with a status code
            // that falls out of the range of 2xx
            console.log('🐔🐔🐔🐔🐔🐔🐔🐔');
            console.log(error.response.data);
            console.log(error.response.status);
            console.log(error.response.headers);
          }
          logger.error(
            { attributes, error, underlying: error?.underlying },
            'counterparties:create-verified-counterparty:error:unit-achCounterparty'
          );

          if (error?.underlying?.data?.errorCode === 'NameVerificationFailed') {
            return new Err(
              new UnitHttpError(
                UnitHttpErrors.NameVerificationFailed,
                error?.underlying?.data?.details || ''
              )
            );
          }
          return Err(error);
        });

      return result;
    } catch (e) {
      const error = unexpectedError(e);
      return Err(error);
    }
  }
}

已尝试的排查步骤

  • 直接用Postman发送请求,接口行为符合预期;
  • 在独立代码沙箱中用Axios调用,接口行为符合预期;
  • 查看node_modules中的源码。

求助问题

请问有什么解决思路?

内容的提问来源于stack exchange,提问作者Jose A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:37:48