错误响应

模拟服务器错误响应。

你可以通过构建有效的错误 Response 实例并从响应解析器返回该实例,使用错误响应来响应拦截的请求。这意味着使用错误状态代码 (4xx/5xx),并可选地提供任何自定义响应负载,例如错误消息。

¥You can respond to the intercepted request with an error response by constructing a valid error Response instance and returning it from the response resolver. This implies using an error status code (4xx/5xx) and optionally providing any custom response payload, such as an error message.

http.get<{ id: string }>('/books/:id', ({ params }) => {
  if (params.id === 'abc-123') {
    return new HttpResponse(null, { status: 404 })
  }
 
  return HttpResponse.json({
    id: params.id,
    title: 'The Lord of the Rings',
  })
})

类型安全

¥Type safety

错误响应的类型安全性取决于你如何定义它们。使用推断预期响应主体类型的简写形式(例如 HttpResponse.text()HttpResponse.json())时,错误响应将保持类型安全:

¥Type safety of your error responses depends on how you define them. When using shorthands that infer the expected response body type, like HttpResponse.text() and HttpResponse.json(), error responses will remain type-safe:

http.get<never, never { id: string } | { error: message }>('/resource', ({ request }) => {
  if (!request.headers.has('authorization')) {
    return HttpResponse.json(
      { error: 'Unauthorized' },
      { status: 401 }
    )
  }
 
  return HttpResponse.json({
    id: 'abc-123',
  })
})

使用普通的 Response 实例会忽略任何响应正文类型,因为其 bodyInit 类型无法缩小 - 它始终是 nullstringReadableStream。对于没有正文的错误响应,请充分利用这一点。

¥Using the plain Response instance ignores any response body types because its bodyInit type cannot be narrowed—it’s always either null, string, or ReadableStream. Use this to your advantage for error responses without a body.