Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ghahramani/110376f2e76acd6317b08c00343c4818 to your computer and use it in GitHub Desktop.
Save ghahramani/110376f2e76acd6317b08c00343c4818 to your computer and use it in GitHub Desktop.
A handler to convert HttpStatusCodeException to ProblemVM
@Component
class HttpStatusCodeExceptionProblemHandler(private val objectMapper: ObjectMapper) :
ProblemExceptionHandler<HttpStatusCodeException> {
override fun supports(clazz: Throwable): Boolean {
return clazz is HttpStatusCodeException
}
override fun generateProblemVM(e: HttpStatusCodeException): ProblemVM {
val status = e.statusCode
var url = when (status) {
HttpStatus.NOT_FOUND -> NOT_FOUND_TYPE
HttpStatus.UNAUTHORIZED -> AUTHORIZATION_TYPE
HttpStatus.FORBIDDEN -> FORBIDDEN_TYPE
else -> INTERNAL_TYPE
}
val body = e.responseBodyAsString
var params: MutableMap<String, Any> = objectMapper.readValue(body)
var message = when (status) {
HttpStatus.NOT_FOUND -> AppConstants.Error.ERR_NOT_FOUND
else -> e.message
}
e.responseHeaders?.contentType?.let { mediaType ->
if (mediaType.includes(MediaType.APPLICATION_PROBLEM_JSON_UTF8)) {
val vm = objectMapper.readValue<ProblemVM>(body)
message = vm.message
params = vm.params
url = vm.url
}
}
return ProblemVM(url, message.orEmpty(), status.value(), params)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment