首页 > 解决方案 > catch 块中的 AxisError 返回错误的状态代码 200

问题描述

对 Salesforece 进行 POST api 调用,无法向客户端返回正确的状态码,它返回的是正确的错误消息但错误的状态码,应该是 400 但返回的是 200

这是调用handleCreateBusinessContactCase函数的请求。

@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 repsone = await createBusinessContactCase(logCtx, requestBody);
    return Promise.resolve(repsone);
  }

.....
return axios({
    url,
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${tokens.authentication}`,
    },
    data: jsonData,
    timeout: 10000
  }).then((response: AxiosResponse<any>) => {
    /*if (response.status === 401) {
      log.debug(`SaleForce refused token, clear the token and try once more, status code: ${response.status}`);
    }*/
    return response.data
  }).catch((error: AxiosError) => {
    console.log(error.response?.data);  
    console.log(error.response?.status);  
    console.log(error.response?.headers); 
    return error.response?.data
  });

这些行的输出与console.log预期的一样,但在 swagger UI 中我得到了正确的消息,但状态码是 200,应该是 400!

这是日志输出

[
  {
    message: "Record Type ID: this ID value isn't valid for the user: 0120Y000000VLBKQA4",
    errorCode: 'INVALID_CROSS_REFERENCE_KEY',
    fields: [ 'RecordTypeId' ]
  }
]
400
{
  date: 'Sun, 10 Oct 2021 23:31:46 GMT',
  'set-cookie': [
    'CookieConsentPolicy=0:1; domain=icelandair--test.my.salesforce.com; path=/; expires=Mon, 10-Oct-2022 23:31:46 GMT; Max-Age=31536000',
    'LSKey-c$CookieConsentPolicy=0:1; domain=my.salesforce.com; path=/; expires=Mon, 10-Oct-2022 23:31:46 GMT; Max-Age=31536000',
    'BrowserId=PDDStioiEeyHw1UM8hQSng; domain=.salesforce.com; path=/; expires=Mon, 10-Oct-2022 23:31:46 GMT; Max-Age=31536000'
  ],
  'strict-transport-security': 'max-age=31536000; includeSubDomains',
  'x-content-type-options': 'nosniff',
  'x-xss-protection': '1; mode=block',
  'x-robots-tag': 'none',
  'cache-control': 'no-cache,must-revalidate,max-age=0,no-store,private',
  'sforce-limit-info': 'api-usage=17224/5000000',
  'content-type': 'application/json;charset=UTF-8',
  'transfer-encoding': 'chunked',
  connection: 'close'
}

标签: typescriptaxios

解决方案


解决方案是首先修改控制器以不总是解决承诺

@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');
    return createBusinessContactCase(logCtx, requestBody);
  }

然后我可以格式化返回的 obj。正如我喜欢这样的处理程序

export  const createBusinessContactCase() = async(): Promise<anty> {
return axios({
    url,
    method: 'post',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${tokens.authentication}`,
    },
    data: jsonData,
    timeout: 10000
  }).then((response: AxiosResponse<any>) => {
    /*if (response.status === 401) {
      log.debug(`SaleForce refused token, clear the token and try once more, status code: ${response.status}`);
    }*/
    return response.data
  }).catch((error: AxiosError) => {
    throw { message: error.response?.data, status: error.response?.status };
  });
};
}

推荐阅读