Next.js Discord

Discord Forum

How do I handle an error in middleware?

Unanswered
togakangaroo posted this in #help-forum
Open in Discord
I wrote a middleware to do simple logging

import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import { createLogger } from './logger'
import { pick } from 'lodash'

const { logInfo } = createLogger({ __filename: "middleware" })

export const middleware = (request: NextRequest) => {
  logInfo('Request', pick(request, 'url', 'method', 'ip'))
    const response = NextResponse.next()
    logInfo('Response', {...pick(request, 'url', 'method'), ...pick(response, 'status')})
    return response
}

export const config = {
  matcher: '/api/:path*',
}


Now I want to log unhandled exceptions in a special manner (by calling my logError function and doing some other logging). I am forcing an error in my api handler for the sake of testing but can't figure out where to put the code to handle it.

Things I have tried
- Examining the response - this doesn't work. Oddly it has status: 200 even though the actual status returned is 500
- Putting the next() call in a try..catch. - This doesn't work, no matter what the catch block is never triggered
- Reading the response.body stream and handling errors on that - again, those seem to somehow never be invoked

What's up?

2 Replies

bump on this
I do notice that the docs technically say

Logging and Analytics: Capture and analyze request data for insights before processing by the page or API.

But hold on, what about after?