简体   繁体   English

从@ExceptionHandler重定向不起作用

[英]Redirect from @ExceptionHandler doesn't work

I have exception handler like this: 我有这样的异常处理程序:

@ControllerAdvice
public classMyExceptionHandler extends ResponseEntityExceptionHandler {
    @ExceptionHandler(MyRuntimeException.class)
    public String handleMyRuntimeException(MyRuntimeExceptionexception ex){
        LOGGER.info(ex.getMessage());
        return "redirect:/www.google.com";
    }
}

I execute http request, I see that Controller handles my request, then MyRuntimeException is throwing and handleMyRuntimeException method is invoking. 我执行HTTP请求,我看到控制器处理我的请求,然后MyRuntimeException被抛handleMyRuntimeException方法调用。 but in postman I see that server returns 401 http status and I don't see www.google.com in response headers. 但在邮递员中,我看到服务器返回401 http状态,并且在响应标头中没有看到www.google.com。

What do I wrong? 我怎么了

First , Postman by default will automatically follow the redirect . 首先,默认情况下,邮递员将自动遵循重定向。 What you get in the Postman is the response that is already redirected to /www.google.com . 您在Postman中得到的是已经重定向到/www.google.com的响应。 Go to setting to turn this off : 转到设置将其关闭:

在此处输入图片说明

Second , redirect:/www.google.com is different from redirect://www.google.com . 其次, redirect:/www.google.comredirect://www.google.com不同。 Assuming your server is 127.0.0.1:8080 : 假设您的服务器是127.0.0.1:8080

  • redirect:/www.google.com --> redirect to http://127.0.0.1:8080/www.google.com redirect:/www.google.com >重定向到http://127.0.0.1:8080/www.google.com
  • redirect://www.google.com --> redirect to http://www.google.com redirect://www.google.com >重定向到http://www.google.com

So you actually redirect back to your server and the 401 error that you received is probably due to your server 's access control. 因此,您实际上重定向回了服务器,并且收到的401错误可能是由于服务器的访问控制所致。

In my case it is working fine, please check: 就我而言,它工作正常,请检查:

@ControllerAdvice
public 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");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM