简体   繁体   中英

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. but in postman I see that server returns 401 http status and I don't see www.google.com in response headers.

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 . Go to setting to turn this off :

在此处输入图片说明

Second , redirect:/www.google.com is different from redirect://www.google.com . Assuming your server is 127.0.0.1:8080 :

  • redirect:/www.google.com --> redirect to http://127.0.0.1:8080/www.google.com
  • redirect://www.google.com --> redirect to 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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