user871611
user871611

Reputation: 3462

CompletableFuture: control http response status-codes

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);
  }
}

Upvotes: 3

Views: 8040

Answers (2)

Victor Petit
Victor Petit

Reputation: 2692

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));
}

Upvotes: 8

kewne
kewne

Reputation: 2298

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 .

Upvotes: 1

Related Questions