Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save prondzyn/7adb7ea3ca00ab476a79ad74e48dcbe5 to your computer and use it in GitHub Desktop.
Save prondzyn/7adb7ea3ca00ab476a79ad74e48dcbe5 to your computer and use it in GitHub Desktop.
Example of proper handing error response in Spring Boot + Swagger while endpoint is producing "image/jpeg"
// imports are here
@RestController
class ImageController {
// This will work, but response content type can be improper.
@GetMapping("/images_1/{id}")
fun getImage1(@PathVariable id: UUID): ByteArray? {
return // bytes of an image
}
// This will work in a happy path.
//
// But in unhappy path (for example when image is not found) you can see exception:
// org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
//
// At least when you are calling from Swagger
// because it adds "-H 'accept: image/jpeg'" header to the request.
//
// The cause of the exception lies in @ExceptionHandler configiration.
// It is very likely that error response is configured to return "application/json"
// and Spring cannot handle this properly.
@GetMapping("/images_2/{id}", produces = [MediaType.IMAGE_JPEG_VALUE])
fun getImage2(@PathVariable id: UUID): ByteArray? {
return // bytes of an image
}
// This will work in both cases and response content types will be correct.
//
// We are forcing swagger to add "-H 'accept: */*'" header instead.
@GetMapping("/images_3/{id}", produces = [MediaType.IMAGE_JPEG_VALUE])
@ApiResponse(
responseCode = "200",
description = "OK",
content = [
Content(
schema = Schema(implementation = ByteArray::class),
mediaType = MediaType.ALL_VALUE
)
]
)
fun getImage3(@PathVariable id: UUID): ByteArray? {
return // bytes of an image
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment