koajs / koa-body

koa body parser middleware
MIT License
950 stars 130 forks source link

How can i throw err in options.formidable's onFileBegin callback #159

Closed tobeapro closed 5 years ago

tobeapro commented 5 years ago

76

Environment Information

Current Behavior

when i set maxFileSize in Options, it is ok; now i need use Options.formidable's formidable onFileBegin, code below

//global catch err
const catchError = async (ctx:any, next:any) => {
    try{
        await next()
    }catch(err){
        console.log(err)
        ctx.status = err.statusCode || err.status || 500;
        ctx.body = {
            code:2,
            msg: err.message
        };
    }
}
app.use(catchError)

app.use(koaBody({
    multipart:true,
    encoding:'utf-8',
    formidable:{
        multiples:false,
        uploadDir:path.join(__dirname,'./public/resource/'), 
        keepExtensions: true,  
        maxFileSize:2 * 1024 * 1024, // exceed can be catch
        onFileBegin(name,file){
            const fileName = file.name;
            const picReg = /\.(png|jpe?g|gif|svg)$/i;
            if(!picReg.test(fileName)){
                throw new Error('only picture') // this operation will stop application
            }
        }
    },
    onError(err:any,ctx){
        console.log(err)
        ctx.throw(err)
    }
}));

Expected Behavior

How do I correctly throw an exception?thanks