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

如何处理接口返回null导致读取loanAdjustmentList属性报错的问题

错误原因

报错是由于接口返回的loanAdjustmentResult字段值为null时,直接访问其下属的loanAdjustmentList属性触发了空指针异常,以下是可落地的解决方案:


方案1:使用可选链+空值合并运算符(最简方案,TS 3.7+/ES2020+环境支持)

直接在取值时增加空判断,取不到值时默认赋值空数组,保证list始终为数组类型:

public list: Array<any> = []; // 建议初始化就给空数组默认值

this.GetList(this.getListRequest)
  .subscribe(
    (resp) => {
      this.progressSpinnerService.stopLoading();
      // 可选链?.判断每一层是否为null/undefined,空值合并??兜底默认值
      this.list = resp?.loanAdjustmentResult?.loanAdjustmentList ?? [];
    },
    (error) => {
      this.progressSpinnerService.stopLoading();
      this.handleServiceError(error);
      this.serviceError = true;
    }
  );

方案2:传统层级条件判断(兼容低版本运行环境)

如果项目不支持新语法,可手动增加层级非空判断,兜底赋值空数组:

this.GetList(this.getListRequest)
  .subscribe(
    (resp) => {
      this.progressSpinnerService.stopLoading();
      if (resp && resp.loanAdjustmentResult !== null && resp.loanAdjustmentResult !== undefined) {
        this.list = resp.loanAdjustmentResult.loanAdjustmentList || [];
      } else {
        this.list = [];
      }
    },
    (error) => {
      this.progressSpinnerService.stopLoading();
      this.handleServiceError(error);
      this.serviceError = true;
    }
  );

方案3:RxJS管道中提前处理数据(更符合响应式编码规范)

把数据校验转换、错误处理逻辑都放到RxJS流中处理,订阅回调只负责最终状态更新,逻辑更解耦:

import { map, catchError, of } from 'rxjs';

this.GetList(this.getListRequest)
  .pipe(
    // 提前转换响应数据,兜底空数组
    map(resp => resp?.loanAdjustmentResult?.loanAdjustmentList ?? []),
    // 统一处理错误
    catchError(error => {
      this.handleServiceError(error);
      this.serviceError = true;
      return of([]); // 错误场景也返回空数组,避免下游订阅出错
    })
  )
  .subscribe((list) => {
    this.progressSpinnerService.stopLoading();
    this.list = list;
  });

额外优化建议

建议增加业务状态码判断,即使接口返回200状态,如果header里的statuscode不是预期的成功值,也按错误场景处理,避免业务失败返回的空结构导致逻辑异常:

map(resp => {
  // 先判断业务状态码是否成功
  if (resp?.header?.statuscode !== '0') {
    throw new Error('业务请求失败');
  }
  return resp?.loanAdjustmentResult?.loanAdjustmentList ?? [];
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:21:03