All posts

Fix Middleware Error in Kotlin

Resolve middleware (interceptor) errors in Kotlin Ktor and Spring Boot applications, covering coroutine context and error propagation.

Kotlin Middleware/Interceptor Errors

In Kotlin, middleware takes the form of Ktor plugins (interceptors) or Spring Boot filters. Errors often stem from coroutine context issues or incorrect interceptor ordering.

Ktor Plugin Errors

Ktor's plugin system uses interceptors on the request pipeline:

// BAD — exception kills the pipeline silently
val AuthPlugin = createApplicationPlugin(name = "Auth") {
    onCall { call ->
        val token = call.request.headers["Authorization"]
        if (token == null) {
            throw UnauthorizedException() // Unhandled!
        }
    }
}

// GOOD — respond with proper status
val AuthPlugin = createApplicationPlugin(name = "Auth") {
    onCall { call ->
        val token = call.request.headers["Authorization"]
        if (token == null) {
            call.respond(HttpStatusCode.Unauthorized, "Missing token")
            return@onCall
        }
    }
}

Ktor Status Pages for Error Handling

install(StatusPages) {
    exception<Throwable> { call, cause ->
        call.respond(
            HttpStatusCode.InternalServerError,
            mapOf("error" to cause.message)
        )
    }
}

Spring Boot Kotlin Filter

@Component
@Order(1)
class LoggingFilter : OncePerRequestFilter() {
    override fun doFilterInternal(
        request: HttpServletRequest,
        response: HttpServletResponse,
        filterChain: FilterChain
    ) {
        val start = System.currentTimeMillis()
        try {
            filterChain.doFilter(request, response)
        } finally {
            val duration = System.currentTimeMillis() - start
            logger.info("${request.method} ${request.requestURI} - ${duration}ms")
        }
    }
}

Always call filterChain.doFilter() — skipping it silently drops the request.

Bugsly captures exceptions from both Ktor and Spring Boot Kotlin applications with full coroutine context.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free