You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Fastify Auth问题:异步方法未执行完成已调用处理器

Fastify Auth 认证逻辑不生效问题排查与修复

问题根源

你代码里的认证函数同时使用了async关键字和done回调,这会导致Fastify无法正确捕获认证错误。Fastify对异步钩子函数的处理逻辑是:如果函数是async的,会优先等待其Promise完成,此时调用done不会被处理,相当于你的错误抛出逻辑被忽略了,所以认证没触发失败,直接进入了handler。

另外你嵌套的OR组里两个函数都抛出错误,按照(f3 OR f4)的逻辑本应触发认证失败,但因为错误没被正确捕获,整个认证链被判定为成功。

修复方案

方案1:移除async,仅使用done回调

去掉认证函数的async关键字,直接通过done传递错误:

preHandler: fastify.auth(
    [
        fastify.verifyJWT,
        [
            (request, reply, done) => {
                console.log('check0');
                console.log('check1');
                done(new Error('you are not authenticated'));
            },
            (request, reply, done) => {
                console.log('check2');
                delay(2000).then(() => {
                    console.log('check3');
                    done(new Error('you are not authenticated'));
                });
            },
        ],
    ],
    { relation: 'and' }
),

方案2:使用async/await,抛出错误代替done

保留async关键字,用throw替代done传递错误:

preHandler: fastify.auth(
    [
        fastify.verifyJWT,
        [
            async (request, reply) => {
                console.log('check0');
                console.log('check1');
                throw new Error('you are not authenticated');
            },
            async (request, reply) => {
                console.log('check2');
                await delay(2000);
                console.log('check3');
                throw new Error('you are not authenticated');
            },
        ],
    ],
    { relation: 'and' }
),

验证效果

修复后,当认证逻辑触发错误时,Fastify会正确返回401状态码,不会进入handler执行,控制台也不会输出te123和请求成功的日志。

内容的提问来源于stack exchange,提问作者wiifree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:12:12