score:-1

In case of failure you can throw custom Exception with proper message. Then you can catch it in @ControllerAdvice. I'll add an example in a moment.

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MyCustomException.class)
    public ResponseEntity<String> exception(MyCustomException e) {

        return new ResponseEntity(e.getMessage(), HttpStatus.NotFound);
    }
}

In one @ControllerAdvice one could have more methods listening for different Exceptions. Custom Exception can hold whatever you want - it's a normal class - so you can return ResponseEntity of whatever you want.

score:-1

For example:

@Transactional(readOnly = true)
@GetMapping("/{id}")
public ResponseEntity<?> getUserById(@PathVariable("id") String userId) {

    return userRepository.findById(userId)
                  .map(user -> ResponseEntity.ok().body(user))
                  .orElse(new ResponseEntity<>(/* new ErrorMessage */, HttpStatus.NOT_FOUND))
}

For 'not found' response you have to create an error message object and return it to client.


Related Query

More Query from same tag