tauren.kristich
tauren.kristich

Reputation: 479

Spring REST best practice for method types

I am building a Spring RESTfull service and a I have the following method that retrieves a Place object based on given zipcode:

@RequestMapping(value = "/placeByZip",  method = RequestMethod.GET)
public Place getPlaceByZipcode(@RequestParam(value="zipcode") String zipcode)   {
    Place place = placeService.placeByZip(zipcode);
    return  place;
}

Is it best practice to have the return type of "Place"? I imagine this is difficult for error handling?

Upvotes: 1

Views: 1830

Answers (2)

Laurentiu L.
Laurentiu L.

Reputation: 6686

A better practice would be to create a Data Transfer Object with only the properties you will be using in the front end.

With a proper JS framework you could easily do proper error handling. (for example you could define a service in AngjularJs which would define the DTO's fields).

Also, you might as well do return placeService.placeByZip(zipCode);


As robinsio suggested it is good practice to add controller advice. You can set the status to some http code (for example HttpStatus.conflict) and have an exception handler (ex. BaseServiceException) which you can throw inside your place service if some validation rules you define are broken.

The controller advice could return a map which you handle in the case of the respective http status code in a consistent manner (let's say a modal appears in the interface to notify of the message you sent from the base service exception).

Upvotes: 0

robinsio
robinsio

Reputation: 93

Using the latest versions of Spring for a RESTfull web service I do believe returning the 'Object' is good practise as it allows you to simplify your code and be specific on what you are returning. I see this as strongly typing your API response.

A good practise for error handling is to use the controller advice utility supplied by spring.

Have a read of:

https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc

This allows you to throw your exceptions at any of your service layers and produce a nice helpful error response.

Upvotes: 1

Related Questions