【发布时间】:2020-08-24 23:24:25
【问题描述】:
请问在 Spring webflux 中抛出已检查的自定义异常的正确方法是什么? 我要坚持,它是关于已检查的自定义异常,比如 MyException.java,而不是 RuntimeException,它是关于 抛出异常,而不是处理异常。
我尝试了以下方法:
@Controller
@SpringBootApplication
public class QuestionHowToThrowException {
public static void main(String[] args) {
SpringApplication.run(QuestionHowToThrowException.class);
}
@PostMapping(path = "/question", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<ResponseEntity<QuestionResponse>> question(@RequestBody QuestionRequest questionRequest) {
Mono<FirstStep> firstStepMono = WebClient.create().post().uri("http://firstWebService:8111/getFirstStep")
.body(questionRequest.getThing(), String.class).retrieve().bodyToMono(FirstStep.class);
Mono<SecondStep> secondStepMono = firstStepMono.map(oneFirstStep -> getSecondStepFromFirstStepAfterCheck(oneFirstStep));
return secondStepMono.map(oneSecondStep -> ResponseEntity.ok(new QuestionResponse(oneSecondStep.getSecondThing())));
}
private SecondStep getSecondStepFromFirstStepAfterCheck(FirstStep firstStep) throws MyException {
if (firstStep.getThingNeedsToCheckCanThrowException().equals("exception")) {
throw new MyException("exception");
} else {
return new SecondStep(firstStep.getThingNeedsToCheckCanThrowException() + "good");
}
}
public class QuestionRequest {
private String thing;
public String getThing() {
return thing;
}
}
public class QuestionResponse {
private String response;
public QuestionResponse(String response) {
this.response = response;
}
}
public class FirstStep {
private String thingNeedsToCheckCanThrowException;
public String getThingNeedsToCheckCanThrowException() {
return thingNeedsToCheckCanThrowException;
}
}
public class SecondStep {
private String secondThing;
public SecondStep(String secondThing) {
this.secondThing = secondThing;
}
public String getSecondThing() {
return secondThing;
}
}
}
这是不可能的,因为 getSecondStepFromFirstStepAfterCheck 方法中存在未处理的异常。
如果我抛出并传播,private SecondStep getSecondStepFromFirstStepAfterCheck(FirstStep firstStep) 抛出 MyException lambda 调用者方法不高兴。
请问在 webflux 中抛出自定义异常的最干净和正确的方法是什么?
谢谢
【问题讨论】:
标签: java spring-boot exception spring-webflux