What does ctx.throw do?
What does ctx.throw do?
About koajs/koa · 2 messages · last activity 7/12/2026
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:
-
ctx.throw(msg)— Throws an error with a 500 status andexpose: false[tests/context/throw.test.js:L6-L14] -
ctx.throw(err)— Throws an existing error, defaulting to 500 status andexpose: false[tests/context/throw.test.js:L17-L27] -
ctx.throw(status, msg)— Throws with a specific HTTP status code and message, setsexpose: truefor valid status codes [tests/context/throw.test.js:L49-L57] -
ctx.throw(status, err)— Throws an existing error and sets the specified status [tests/context/throw.test.js:L36-L45] -
ctx.throw(status, msg, props)orctx.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 inexpose: false[tests/context/throw.test.js:L71-L79] - Property Mixing: Additional properties can be mixed into the error object, and any
statusproperty 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/koaPublic Q&A. Generated by RepoPilot from the actual source of koajs/koa. AI answers can be incomplete or stale — verify before relying on them.