【发布时间】:2018-09-12 06:10:33
【问题描述】:
我有两个 @RestControllers -(A 和 B)并注册了 ResponseEntityExceptionHandler。在应用异常处理程序后,是否可以(以及如何做)从A 调用并从B 获得响应?
例子:
- 用户休息电话
A -
A与getPerson通话B -
B抛出异常NotFound -
NotFound由异常处理程序处理,转换ResponseEntity并放入 400 状态 -
B终于返回异常ResponseEntity -
A从B获得 400 状态 -
A可以得到这个 400 并用它做点什么
简单的@Autowired 不起作用。
片段:
答:
@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;
}
}
【问题讨论】:
-
你能放一些代码sn-p吗?
-
或多或少会像我更新了一样。
-
可能会在哪一行抛出MyException?是 logicService.addPerson(person) 吗?
-
MyException 可以是 accessService 的 accessException,也可以是逻辑服务的 notfoundexception/badrequestexception 等。
-
ByeBye 可能是您缺少“@Component 或 @Service”注释。请检查 accessService 或逻辑服务上的注释。
标签: java spring exception-handling