RepoPilot

What does ctx.throw do?

About koajs/koa · 2 messages · last activity 7/12/2026

Question

What does ctx.throw do?

RepoPilot

ctx.throw is a method in Koa's context that throws an error with specific HTTP status and message handling. Based on the test cases in the repository, here's what it does:

Core Functionality

ctx.throw creates and throws an error object that is handled by Koa's error handling system. It supports multiple signatures:

  1. ctx.throw(msg) — Throws an error with a 500 status and expose: false [tests/context/throw.test.js:L6-L14]

  2. ctx.throw(err) — Throws an existing error, defaulting to 500 status and expose: false [tests/context/throw.test.js:L17-L27]

  3. ctx.throw(status, msg) — Throws with a specific HTTP status code and message, sets expose: true for valid status codes [tests/context/throw.test.js:L49-L57]

  4. ctx.throw(status, err) — Throws an existing error and sets the specified status [tests/context/throw.test.js:L36-L45]

  5. ctx.throw(status, msg, props) or ctx.throw(status, props) — Allows mixing in additional properties to the error object [tests/context/throw.test.js:L91-L104] and [tests/context/throw.test.js:L141-L150]

Key Behaviors

  • Status Validation: Only valid HTTP status codes set expose: true; invalid statuses (like -1 or 9999) result in expose: false [tests/context/throw.test.js:L71-L79]
  • Property Mixing: Additional properties can be mixed into the error object, and any status property in the props is ignored in favor of the explicitly passed status [tests/context/throw.test.js:L106-L117]

FOLLOW_UPS:

  • How does Koa handle errors thrown by ctx.throw?
  • What does the expose property indicate on errors?
  • How can custom error handlers be implemented in Koa?

Want to ask your own question?

Open chat for koajs/koa

Public Q&A. Generated by RepoPilot from the actual source of koajs/koa. AI answers can be incomplete or stale — verify before relying on them.