猿问

从@ExceptionHandler 重定向不起作用

我有这样的异常处理程序:


@ControllerAdvice

public classMyExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(MyRuntimeException.class)

    public String handleMyRuntimeException(MyRuntimeExceptionexception ex){

        LOGGER.info(ex.getMessage());

        return "redirect:/www.google.com";

    }

}

我执行 http 请求,我看到 Controller 处理了我的请求,然后MyRuntimeException正在抛出并且handleMyRuntimeException正在调用方法。但在邮递员中,我看到服务器返回 401 http 状态,而我在响应标头中看不到 www.google.com。


我错了什么?


冉冉说
浏览 482回答 2
2回答

白猪掌柜的

首先,Postman 默认会自动跟随重定向。您在 Postman 中得到的是已经重定向到的响应/www.google.com。转到设置将其关闭:二redirect:/www.google.com是不同redirect://www.google.com 。假设您的服务器是127.0.0.1:8080:redirect:/www.google.com --> 重定向到 http://127.0.0.1:8080/www.google.comredirect://www.google.com--> 重定向到http://www.google.com所以你实际上重定向回你的服务器,你收到的 401 错误可能是由于你的服务器的访问控制。

弑天下

就我而言,它工作正常,请检查:@ControllerAdvicepublic class ErrorHandler {    @ExceptionHandler(CustomRuntimeException.class)    @ResponseStatus(value=HttpStatus.OK)    public ModelAndView handleCustomRuntimeException(HttpServletRequest request, HttpServletResponse response, Exception ex) {        ModelAndView mav = new ModelAndView("error");        mav.addObject("error", "500");        return mav;        //return new ModelAndView("redirect:https://www.google.com");    }}
随时随地看视频慕课网APP

相关分类

Java
我要回答