In JAX RS, differences between returning Response and Bean or Collection of Beans (DTO)

前端 未结 3 1231
终归单人心
终归单人心 2021-01-30 04:08

I am working on building a REST api. My question is, when using Jersey, what are the differences between my services building and returning a Response object or returning the th

3条回答
  •  情歌与酒
    2021-01-30 04:42

    My personal of view, if response contains DTO (Bean/Collection of beans), then rest service always must return DTO, but not Response object.

    The motivation: early or late, you will be asked to make a usage of rest service easier for clients, by providing rest client api. Usually, you have to extract rest interfaces for it, and implement them with your rest services. These rest interfaces are used by clients of your rest client.

    And from a client point of view there is a huge difference between processing DTO and plain Response. In case Response is used, your client is forced:

    1. Check response code explicitely to process successfull response
    2. Handle errors, by checking codes explicitly
    3. Convert body of your response into DTO by himself.

    Which means handling Response is very similar to returning error codes in methods, which is considered as a very bad practice. In order to handle errors in one place, exceptions are used (I'm not talking about FP ways of handle errors, which is the best).

    So what may you do:

    1. In case a request is processed successfully, convert in your rest service data into DTO/Bean and return it.
    2. In case if validation failed, or something went wrong, throw an exception in your rest service. Perhaps a default exception mapper is not good for you, so, you'll have to implement your own exception mapper.

    So if to think in advance, you should return DTO.

    One use-case, when plain Response should be returned - when you export file, for instance. It seems JAX RS does not allow to return InputStream object. Not sure, it has to be checked.

    The other use case, was pointed by @Perception, but it is more an exception, than a rule:

    Methods that need to provide additional metadata with a response should return an instance of Response, the ResponseBuilder class provides a convenient way to create a Response instance using a builder pattern.

    Note: it is a general question for JAX RS, does not depend on exact implementation, like Resteasy or Jersey

提交回复
热议问题