我正在尝试执行以下操作。我希望能够在myController中设置infoVar并在MyResponseEntityExceptionHandler中获取它。我尝试设置正确的范围(我认为是Request),但是我不断收到类似于以下内容的错误:

Caused by: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.


控制者

@RestController()
public class myController() {
  @Autowired private InfoVar infoVar;

  @PostMapping(path = "/stuff")
  public @ResponseBody sutff getStuff(@RequestBody String string)   throws Exception {
    infoVar.setVar("Test123");
    return stuff;
  }
}


错误处理

@ControllerAdvice
@RestController
public class MyResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @Autowired private InfoVar infoVar

    @ExceptionHandler(Exception.class)
    public final ResponseEntity<Object> handleStuff(Exception ex, WebRequest request) {
        infoVar.getVar();
        return stuff;
    }
}


infoVar

@Component
@Scope("request")
public class InfoVar{
    private String infoVar;
getter and setter for infovar
}

最佳答案

我确实提出了解决方案,但我不喜欢它。我觉得应该有一种使用bean而不是添加到WebRequest中的方法。

控制者

@RestController()
public class MyController() {

  @PostMapping(path = "/stuff")
  public @ResponseBody sutff getStuff(@RequestBody String string)   throws Exception {
    InfoVar infoVar = new InfoVar();
    infoVar.setVar("Test123");
    webRequest.setAttribute("infoVar", infoVar, WebRequest.SCOPE_REQUEST);
    return stuff;
  }
}


错误处理

@ControllerAdvice
public class MyResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity<Object> handleStuff(Exception ex, WebRequest request) {
        InfoVar infoVar = (InfoVar) request.getAttribute("infoVar", WebRequest.SCOPE_REQUEST);
        infoVar.getVar();
        return stuff;
    }
}


InfoVar

public class InfoVar{
    private String var;
getter and setter for var
}

08-08 01:09