为了账号安全,请及时绑定邮箱和手机立即绑定

Spring - 通过异常处理程序拦截来自另一个 bean 的响应

Spring - 通过异常处理程序拦截来自另一个 bean 的响应

翻翻过去那场雪 2021-09-15 14:32:05
我有两个@RestControllers -(A 和 B)并注册了ResponseEntityExceptionHandler. 是否有可能(以及如何做到)在应用异常处理程序后调用A并获得响应B?例子:用户休息电话 AA电话B与getPersonB 抛出异常 NotFoundNotFound由异常处理程序处理,转换ResponseEntity并放置 400 状态B 最后返回异常 ResponseEntityA 获得 400 状态 BA 可以得到这个 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)        );    }}处理程序@ControllerAdvicepublic final class MyExceptionHandler extends ResponseEntityExceptionHandler {    @ExceptionHandler(MyException.class)    protected ResponseEntity<Object> handleApiException(final MyException exception, final WebRequest webRequest) {        //logic        return afterLogic;    }}
查看完整描述

2 回答

?
万千封印

TA贡献1891条经验 获得超3个赞

forward 就像重定向,但完全发生在服务器端;Servlet 容器将相同的请求转发到目标 URL;URL 在浏览器中不会改变。在春天你可以这样做,你可以传递属性:


@Controller

@RequestMapping("/")

public class YourController {


    @GetMapping("/forward")

    public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) {

        model.addAttribute("attribute", "forward");

        return new ModelAndView("forward:/redirectedUrl", model);

    }

}


查看完整回答
反对 回复 2021-09-15
  • 2 回答
  • 0 关注
  • 143 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信