获取自定义错误控制器中的异常对象

use*_*702 7 spring-boot

我正在使用 spring boot 并编写一个全局异常处理程序 use AbstractErrorController。我如何在控制器中获取异常对象?

@Controller
public class MyCustomErrorController extends AbstractErrorController {

    public MyCustomErrorController(ErrorAttributes errorAttributes) {
        super(errorAttributes);
    }

    @RequestMapping("/error")
    public void handleError(HttpServletRequest req, HttpServletResponse resp) {
        Exception e = ...; // how to get exception here
        log.error(e);
        displayError(req, resp, e);
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
Run Code Online (Sandbox Code Playgroud)

trf*_*trf 5

您可以从 HttpServletRequest 获取异常,如下所示:

    @Controller
    public class MyCustomErrorController extends AbstractErrorController {
    
        @RequestMapping("/error")
        public void handleError(HttpServletRequest request) {
            Exception e = (Exception) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
            ...
        }
    }
Run Code Online (Sandbox Code Playgroud)