hoangvvo / next-connect

The TypeScript-ready, minimal router and middleware layer for Next.js, Micro, Vercel, or Node.js http/http2
https://www.npmjs.com/package/next-connect
MIT License
1.64k stars 65 forks source link

Can not catch error when using async and await #205

Closed sendking closed 2 years ago

sendking commented 2 years ago

https://github.com/sendking/next-connect/pull/1/files

Some problems when i use cors middleware first...

nakashkumar commented 2 years ago

It is probably because cors middleware isn't awaiting next().

// BAD: This will lead to UnhandledPromiseRejection
router
  .use(async (req, res, next) => {
    next();
  })
  .use(async (req, res, next) => {
    next();
  })
  .use(async () => {
    throw new Error("💥");
  });

// GOOD
router
  .use(async (req, res, next) => {
    await next(); // next() is awaited, so errors are caught properly
  })
  .use((req, res, next) => {
    return next(); // this works as well since we forward the rejected promise
  })
  .use(async () => {
    throw new Error("💥");
    // return new Promise.reject("💥");
  });
sendking commented 2 years ago

@nakashkumar

// This way is useful, but i think is not the best.
 router.use(async (req, res, next) => {
   await cors()
   await next()
})

// This way will be broken, but maybe better.
router.use(cors())
tianyingchun commented 2 years ago

face this issue too , v0.12.2 is works fine.

tianyingchun commented 2 years ago
function apiHandler(req, res) {
     // here there are some error throw from handler , the next process will be exit.
     // handler is `async` 
      return handler(req, res, getConfig(config), ops, opts);
   };

use(...).post(async (req, res) => {
   return apiHandler(req, res)
 // if error throw  from. apiHandler(), the whole process will be exit.
});
hoangvvo commented 2 years ago

To use express middleware in v1, you must wrap it with expressWrapper (on latest next version)

import { createRouter, expressWrapper } from "next-connect";
import cors from "cors";

const router = createRouter();
router.use(expressWrapper(cors());

See https://github.com/hoangvvo/next-connect#expressjs-compatibility

sendking commented 2 years ago

It works fine in https://www.npmjs.com/package/next-connect/v/1.0.0-next.3. Thx! 😊