bh4r4th
1 supporter
Interceptor: @Deprecated warning in resp ...

Interceptor: @Deprecated warning in response

Oct 13, 2022

This is an interesting topic,

Until recently, I used mark my old endpoints in @RestController with @Deprecated method. When I checked how it look like on client end, to my surprise I couldn't even tell the endpoint is actually deprecated.

Then I went digging in common conventions, so most suggested to add Warning header to response without changing the status code. I love using spring, so I created this little interceptor class to handle this across my rest api.

Endpoint:

@Deprecated("/poc/v1/features/feature", ReplaceWith("/v1/features/feature"))
@GetMapping("/poc/v1/features/feature")
fun retrieveFeature(): FeatureRespDto {
        return myFeatureService.doSomething()
}

Interceptor Handler Class:

class EndpointDeprecationWarningHeaderInterceptor : HandlerInterceptor {
    @Throws(Exception::class)
    override fun preHandle(request: HttpServletRequest, response: HttpServletResponse, handler: Any): Boolean {
        if (handler is HandlerMethod) {
            if (handler.method.isAnnotationPresent(Deprecated::class.java)) {
                val annotation: Deprecated = handler.method.getAnnotation(Deprecated::class.java)
                response.addHeader(
                    HttpHeaders.WARNING,
                    "Deprecation: ${annotation.message} is replaced with ${annotation.replaceWith.expression}"
                )
            }
        }
        return true
    }
}

Add this Interceptor to security config class of your application that implements WebSecurityConfigurerAdapter class by overriding following function:

override fun addInterceptors(registry: InterceptorRegistry) {
        registry.addInterceptor(EndpointDeprecationWarningHeaderInterceptor())
}

That's it....!!!

Now, GET: /poc/v1/features/feature will still work like before, but when you check the response header then you will find a `Warning` header.

Enjoy this post?

Buy bh4r4th a coffee

More from bh4r4th