1

I have a client that consumes an input stream from a service, like this:

@Client(value = 'http://localhost:8080/')
interface StreamClient {

    @Get(uri = '/data', processes = MediaType.APPLICATION_OCTET_STREAM)
    @Header("Accept: application/octet-stream")
    Flowable<byte[]> retrieveFile()
}

and when using it like this (Groovy):

void getContent(OutputStream outputStream) {
    client.retrieveFile().blockingSubscribe({ byte[] bytes ->
        outputStream.write(bytes)
    }, { Throwable error ->
        error.printStackTrace()
    })
}

it retrieves the stream just fine without reading the entire byte[] array into memory (exactly as I want it), but if the endpoint returns a 404, I just get an empty byte array, not an error as I would expect.

What am I doing wrong?

saw303
  • 8,051
  • 7
  • 50
  • 90
sbglasius
  • 3,104
  • 20
  • 28
  • In the question I'm using RxJava3 but if Reactor framework has a viable solution I have no problem switching. – sbglasius May 23 '23 at 13:27

1 Answers1

0

The Micronaut http client returns the declared return type (in your case byte[]) for status 2xx and 404. In the case of 404 you usually get null for objects and in your case with a primitive array it seems to be an empty array.

In order to get more control I recommend to return an HttpResponse<byte[]>. With this type you get access to the http status code.

Further readings about error responses and Micronaut http client.

If an HTTP response is returned with a code of 400 or higher, an HttpClientResponseException is created. The exception contains the original response. How that exception gets thrown depends on the return type of the method. For blocking clients, the exception is thrown and should be caught and handled by the caller. For reactive clients, the exception is passed through the publisher as an error.

saw303
  • 8,051
  • 7
  • 50
  • 90
  • thanks, but I need it to be reactive, as I'm potentially streaming +1GB files from the endpoint I'm calling. Using `HttpReponse` I suspect will stream the entire content to memory, instead of in chunks? – sbglasius May 23 '23 at 13:40
  • To be honest, I don't know. I haven't tried yet. But maybe you could work with StreamedFile (https://docs.micronaut.io/latest/guide/index.html#transfers)? – saw303 May 23 '23 at 13:49