WebFlux 学习笔记
1. WebFlux business exception 处理
代码不完整,主要是记录思想:
private static final String STUDENT_NOT_FOUND_BY_ID = "Student of (name:%s) doesn't exist";
private static final String STUDENT_SCORE_NOT_FOUND_BY_ID = "StudentScore (studentId:%s) doesn't have any scores";
public Mono<StudentScore> findStudentScore(List<String> studentNames) {
return studentService.findStudentByName(studentNames) //1 返回Flux<StudentEntity>
.switchIfEmpty(Mono.error(notFound(STUDENT_NOT_FOUND_BY_ID, userId))) // 2 返回业务错误信息1
.collectList() // 3 转换成Mono<Collection<StudentEntity>>
.flatMapMany(studentEntities -> {
// 4 进行其他的业务处理
Flux<StudentScore> studentScores = studentScoreService.findStudentScore(studentEntities.getStudentIds());
return studentScores;
})
.switchIfEmpty(Mono.error(notFound(STUDENT_SCORE_NOT_FOUND_BY_ID, userId)));// 5 返回业务错误信息2
}
private ResponseStatusException notFound(String errorInfo) {
return new ResponseStatusException(HttpStatus.NOT_FOUND,
Optional.ofNullable(errorInfo).orElse(HttpStatus.NOT_FOUND.getReasonPhrase()));
}