Issue
I am currently building a ReST service using spring.
The way I have it set up now is all of my endpoints are returning a ResponseEntity with associated status code and whatever POJO is associated with the request.
A GET request can look something like this
@RequestMapping( value="{id}", method = RequestMethod.GET)
public ResponseEntity<?> getFoo( @PathVariable(value="id") Long id )
{
LOG.info("Getting Foo by ID: " + id);
Foo foo = fooQuery.getFoo( id );
if( foo != null )
return new ResponseEntity<Foo>( foo, HttpStatus.OK );
else
return new ResponseEntity<Void>( HttpStatus.NOT_FOUND );
}
Just wondering if this seems correct or if there is some other standard I should be following.
Solution
I find it simpler to throw exceptions, and use a @ControllerAdvice
class to process all the exceptions. For example, here is a way I would write your code:
@GetMapping(value="{id}")
public Foo getFoo( @PathVariable(value="id") Long id )
{
LOG.info("Getting Foo by ID: " + id);
Foo foo = fooQuery.getFoo( id );
MyUtil.validate(foo != null, "errorMessageCode");
... process foo
return foo;
}
MyUtil.validate
would check for the condition and throw an exception, say MyException
. Then, I would have a @ControllerAdvice
class:
@ControllerAdvice
public class DefaultExceptionHandler {
@RequestMapping(produces = "application/json")
@ExceptionHandler(MyException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public @ResponseBody Map<String, Object>
handleMyException(MyException ex) {
return MyUtil.mapOf("exception", "MyException",
"message", ex.getMessage());
}
If fooQuery.getFoo
would return a Java 8 Optional, as in case of Spring Data Repositories, we can also use this construct to throw exceptions:
Foo foo = fooQuery.getFoo(id).orElseThrow(() ->
new MyException("messageCode");
If it's helpful, here is a nice post on how to handle exceptions using @ControllerAdvice and orher alternatives.
(The above is actually a simpler version of a pattern that is used in an open source project.)
Answered By - Sanjay
Answer Checked By - Timothy Miller (JavaFixing Admin)