Two possible responses on the same endpoint

55 views Asked by At

My application has an aspect that checks if the request is duplicated within a TTL and returns the endpoint result or a message.

This is my controller

 @RestController
@RequestMapping("/results/shares")
class MyController(
    private val myService: MyService,
) {

    private val responseHeaders = HttpHeaders().apply {
        contentType = MediaType.APPLICATION_PDF
        set("Content-Disposition", "attachment; filename=fatura.pdf")
    }

    @LogProfiler
    @LogInfo(logParameters = true)
    @CacheMessageResponse(ttl = 60, false)
    @PostMapping("/email/{invoiceId}")
    fun sendByEmail(
        @RequestHeader("clientId") clientId: String,
        @PathVariable id: String,
    ): EmaileResponse =
        myService.sendInvoiceByEmail(id, clientId).toEmailCompleteResponse()

   
    @CacheRequest(ttl = 60, false)
    @GetMapping("/file/{id}", produces = [MediaType.APPLICATION_PDF_VALUE])
    fun sendFile(
        @RequestHeader("clientId") clientId: String,
        @PathVariable Id: String,
    ): ResponseEntity<Resource> =
        ResponseEntity(myService.retrieveFile(id, clientId), responseHeaders, HttpStatus.OK)
}

Inside the aspect I do a check and if it is in TTL I throw an exception, otherwise the endpoint calls the service and continues the process normally

    if (cachedValue != null) {
            throw DuplicateRequestOnTtlException("Duplicate Error")
        }


class DuplicateRequestOnTtlException(message: String) : RuntimeException(message)

In my Controller exception handler I handle exceptions

@ExceptionHandler(DuplicateRequestOnTtlException::class)
@ResponseBody
fun handleDuplicateRequestOnTtlException(e: DuplicateRequestOnTtlException): ResponseEntity<DuplicateRequestOnTtlErrorResponse> {
    val errorResponse = DuplicateRequestOnTtlErrorResponse(properties.download.message)
    return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS).body(errorResponse)
}


data class DuplicateRequestOnTtlErrorResponse(val message: String)

Everything works as expected for the sendByEmail endpoint, it returns ResponseEntity when necessary, however, with the sendFile endpoint this does not happen, When it is inside the ttl and is to respond to a DuplicateRequestOnTtlErrorResponse gives: Spring cannot handle the response an org.springframework.web.HttpMediaTypeNotAcceptableException: No acceptable representation is thrown and I can't deal with it because I get an Ambiguous @ExceptionHandler in advice

0

There are 0 answers