3

I'm currently struggeling returning http response status-codes on certain conditions. Let's say, the return objetct of taskService.getNewTasks is null. In this case I want to return status-code 404. On some exception I want to return some 50x, and so on.

My code so far

@RestController
public class TaskController {

  @Autowired
  private TaskService taskService;

  @GetMapping(path = "gettasks")
  private Future<Tasks> getNewTasks() {
    return taskService.getNewTasks();
  }
  ...
}

@Service
public class TaskService {

  @Async
  public Future<Tasks> getNewTasks() {
    ...
    return CompletableFuture.completedFuture(tasks);
  }
}
user871611
  • 3,307
  • 7
  • 51
  • 73

2 Answers2

8

This could suit you.

@GetMapping(path = "gettasks")
private CompletableFuture<ResponseEntity<Tasks>> getNewTasks() {
  CompletableFuture<Tasks> future = new CompletableFuture<>();
  future.complete(taskService.getNewTasks());
  if(yourCondition){
    return future.thenApply(result -> new ResponseEntity<Tasks>(result, HttpStatus.STATUS_1));
  }
  return future.thenApply(result -> new ResponseEntity<Tasks>(result, HttpStatus.STATUS_2));
}
Victor Petit
  • 2,632
  • 19
  • 19
1

As described in https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-return-types, Future isn’t supported as return type for controller handler methods. Since you’re using CompletableFuture you can just return that or CompletionStage, which are supported by spring. If that completes with an exception, you can use the regular Spring exception handling mechanisms like annotating the exception with @ResponseStatus .

kewne
  • 2,208
  • 15
  • 11