Open1
[Hono]Responseオブジェクトが返却されていない、もしくはawait next()が呼ばれていない際のエラー

エラー内容
191 | const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
192 | return (async () => {
193 | try {
194 | const context = await composed(c);
195 | if (!context.finalized) {
196 | throw new Error(
^
error: Context is not finalized. Did you forget to return a Response object or await next()?
at <anonymous> (/app/recipe-mgr/node_modules/hono/dist/hono-base.js:196:17)
エラーの内容
このエラーは、Hono(軽量なJavaScript/TypeScript向けのWebフレームワーク)を使っているときに、middleware(ミドルウェア)またはhandler内でResponseオブジェクトが返却されていない、もしくはawait next()が呼ばれていないことによって発生しています。
該当コード要点
const composed = compose(matchResult[0], this.errorHandler, this.#notFoundHandler);
return (async () => {
try {
const context = await composed(c); // c: Context
if (!context.finalized) {
throw new Error("Context is not finalized...");
}
ここで composed(c) を実行していますが、その中に含まれるいずれかのhandlerやmiddlewareが、レスポンスを返さなかったか、await next() を実行していない可能性が高いです。
解決方法
以下のどちらか(または両方)を確認してください:
- Handler関数の中でreturn c.text(), return c.json(), return new Response(...)など、レスポンスを返しているか?
- もしそれがmiddlewareであれば、await next()を呼んで次の処理に渡しているか?
例:正しいミドルウェアの書き方
app.use(async (c, next) => {
console.log("middleware start");
await next(); // これがないと次に進まない
console.log("middleware end");
});
例:正しいhandlerの書き方
app.get("/hello", (c) => {
return c.text("Hello, world!"); // 必ずレスポンスを返す
});
今回エラーになっていた箇所
app.get("/hoge", async (c) => {
const apiUrl = Bun.env.HOGE_API;
if (!apiUrl) {
return c.json({ error: "Failed to fetch category data." }, 502);
}
try {
const response = await fetch(apiUrl);
if (!response.ok) {
return; // ← ❌ ここで何も返してない
}
const json = await response.json();
...
💡 なぜこれがダメなのか?
Honoでは、必ず何かしらのレスポンス(Responseオブジェクト)を返さないと Context が「finalized(完了)」されたとみなされません。
return; だけだと「処理が終わった」けど「レスポンスを返してない」状態になり、エラーになるわけです。
修正案
if (!response.ok) {
return c.json({ error: "Failed to fetch category data." }, 502); // ✅ エラーレスポンスを返す
}