翻翻過(guò)去那場(chǎng)雪
2021-09-15 14:32:05
我有兩個(gè)@RestControllers -(A 和 B)并注冊(cè)了ResponseEntityExceptionHandler. 是否有可能(以及如何做到)在應(yīng)用異常處理程序后調(diào)用A并獲得響應(yīng)B?例子:用戶休息電話 AA電話B與getPersonB 拋出異常 NotFoundNotFound由異常處理程序處理,轉(zhuǎn)換ResponseEntity并放置 400 狀態(tài)B 最后返回異常 ResponseEntityA 獲得 400 狀態(tài) BA 可以得到這個(gè) 400 并用它做點(diǎn)什么簡(jiǎn)單@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) ); }}處理程序@ControllerAdvicepublic final class MyExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(MyException.class) protected ResponseEntity<Object> handleApiException(final MyException exception, final WebRequest webRequest) { //logic return afterLogic; }}
2 回答

萬(wàn)千封印
TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
forward 就像重定向,但完全發(fā)生在服務(wù)器端;Servlet 容器將相同的請(qǐng)求轉(zhuǎn)發(fā)到目標(biāo) URL;URL 在瀏覽器中不會(huì)改變。在春天你可以這樣做,你可以傳遞屬性:
@Controller
@RequestMapping("/")
public class YourController {
@GetMapping("/forward")
public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) {
model.addAttribute("attribute", "forward");
return new ModelAndView("forward:/redirectedUrl", model);
}
}
添加回答
舉報(bào)
0/150
提交
取消