无法触发requestError拦截器

时间:2019-02-20 13:25:04

标签: aurelia aurelia-http-client

我想在处理请求之前检查用户令牌是否有效,并且正在使用拦截器进行操作。

以下是代码:

  request: (request: RequestMessage): any => {
    return new Promise((resolve, reject) => {
      console.log('token expires at', this.expiresAt);
      if (this.isTokenExpired()) {
        console.log('token expired');
        throw new Error("{ message: 'Session expired', statusCode: 401 }");
      }

      if (this.accessToken) {
        this.setAuthorizationHeaders(request);
      }
      resolve(request);
    });
  },
  requestError: (error): any => {
    console.log('request error', error);
    throw new Error(`yo ${error}`);
  }

但是,虽然我在控制台中看到错误,但似乎从未经历过requestError。 我已经在源代码中查看了Interceptor方法的单元测试,但没有发现与我在这里尝试的有太大不同。我在做什么错了?

编辑: 添加HttpClient配置代码:

const request = this.httpClient
  .createRequest(url)
  .withBaseUrl(this.baseUrl)
  .withHeader('Accept', 'application/json');

// Interceptor ?
if (withInterceptor) {
  request.withInterceptor(this.interceptor);
}

// Content type
if (contentType) {
  request.withHeader('Content-Type', contentType);
}

// Params
if (params != null) {
  request.withParams(params);
}

// Data
if (data != null) {
  request.withContent(urlEncode ? UrlUtils.encodeQueryData(data) : data);
}

// Method
switch (method) {
  case 'GET':
    request.asGet();
    break;
  case 'POST':
    request.asPost();
    break;
  case 'PUT':
    request.asPut();
    break;
  case 'DELETE':
    request.asDelete();
    break;
}

1 个答案:

答案 0 :(得分:1)

以下来自官方文档:

requestError acts as a Promise rejection handler during Request creation and request interceptor execution. It will receive the rejection reason, and can either re-throw, or recover by returning a valid Request.

您可以看到,仅在请求创建过程中出现错误时才输入requestError:标头格式错误,配置无效等。

您在此问题中提出的用法完全正确,因此不会requestError出错。