我有两个@RestController
s -(A 和 B)并注册了ResponseEntityExceptionHandler
. 是否有可能(以及如何做到)在应用异常处理程序后调用A
并获得响应B
?
例子:
用户休息电话 A
A
电话B
与getPerson
B
抛出异常 NotFound
NotFound
由异常处理程序处理,转换ResponseEntity
并放置 400 状态
B
最后返回异常 ResponseEntity
A
获得 400 状态 B
A
可以得到这个 400 并用它做点什么
简单@Autowired
是行不通的。
片段:
A:
@RestController
@RequestMapping("/v1")
public class A {
private final B b;
@Autowired
public A(B b) {
this.b = b;
}
@PostMapping(
value = "persons",
consumes = "application/json",
produces = "application/json")
public ResponseEntity<List<StatusResponse<Person>>> addPersons(final List<Person> persons) {
final List<StatusResponse<Person>> multiResponse = new ArrayList<>();
for(final Person p: persons) {
final ResponseEntity<Person> response = b.addPerson(person);
multiResponse.add(new StatusResponse<>(
response.getStatusCode(), response.getMessage(), response.getBody()
));
}
return ResponseEntity.status(HttpStatus.MULTI_STATUS).body(multiResponse);
}
}
乙:
@RestController
@RequestMapping("/v1")
public class B {
@PostMapping(
value = "person",
consumes = "application/json",
produces = "application/json")
public ResponseEntity<Person> addPerson(final Person person) {
accessService.checkAccess();
return ResponseEntity.status(201).body(
logicService.addPerson(person)
);
}
}
处理程序
@ControllerAdvice
public final class MyExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(MyException.class)
protected ResponseEntity<Object> handleApiException(final MyException exception, final WebRequest webRequest) {
//logic
return afterLogic;
}
}
万千封印
相关分类