Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Next Js App router catch-all error handler #234

Open
thomasheimh opened this issue Jul 28, 2023 · 4 comments
Open

Next Js App router catch-all error handler #234

thomasheimh opened this issue Jul 28, 2023 · 4 comments

Comments

@thomasheimh
Copy link

How to use next connect catch-all error handler with app router?

interface RequestContext {
  params: { id: string }
}
const router = createEdgeRouter<NextRequest, RequestContext>()

where should I add the below to catch error

function onError(err, req, res) {
  logger.log(err);
  // OR: console.error(err);

  res.status(500).end("Internal server error");
}
@nocodehummel
Copy link

nocodehummel commented Aug 28, 2023

I am using a factory function that returns the NodeRouter object resulting from createRouter(). Each endpoint calls the factory and adds the endpoint specifics. The last call is the handler() which uses standard handlerOptions object as catch-all error handler.

@demirtasdurmus
Copy link

Could you please provide your example for this solution?

@silvaezequias
Copy link

silvaezequias commented Feb 21, 2024

How to use next connect catch-all error handler with app router?

interface RequestContext {
  params: { id: string }
}
const router = createEdgeRouter<NextRequest, RequestContext>()

where should I add the below to catch error

function onError(err, req, res) {
  logger.log(err);
  // OR: console.error(err);

  res.status(500).end("Internal server error");
}

Man, this worked for me: #202 (comment)

@DNoel26
Copy link

DNoel26 commented Mar 7, 2024

I've used below (rough example) to catch unhandled errors in my app router / middleware. Might be useful for someone.

const initMiddleware = async (req, _, next) => {
  const start = Date.now();

  // for any unhandled errors in subsequent middlewares
  let _next;
  try {
      _next = await next();
  } catch (err) {
      // can log error here 
      // can change how errors are handled below to suit your preference
      if (err instanceof SomeSpecificError) {
        // handle and return response
      }
      if (err instanceof ZodError) {
       return NextResponse.json({ ok: false }, { status: 422 });
     }
      if (err instanceof Error) {
          return NextResponse.json({ ok: false }, { status: 500 });
      }
      return NextResponse.json({ ok: false }, { status: 500 });
  } finally {
      const end = Date.now();
      // can do whatever such as adding logs here
      console.log(`request took ${end - start}ms`)
  }

    return await _next;
}

export const router = createEdgeRouter()
  // ensure to set this as the first middleware otherwise errors
  // won't be caught in the ones before it
  .use(initMiddleware)
  .clone()

I saw the example below suggested somewhere but I've not been able to get it to work for me in the app router

export const createAppRouterWithErrorHandling = () => {
    const router = createEdgeRouter();
    const handler = router.handler.bind(router);

    router.handler = () =>
        handler({
            onError: function() {},
            onNoMatch: function() {}
        });
    return router;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants