gstackoverflow
gstackoverflow

Reputation: 36984

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?

Upvotes: 0

Views: 1572

Answers (2)

Mohd Yasin
Mohd Yasin

Reputation: 483

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

Upvotes: -3

Ken Chan
Ken Chan

Reputation: 90467

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 :

enter image description here

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.

Upvotes: 1

Related Questions