Home > database >  How can I redirect URL in case of exception or invalid input with Sping?
How can I redirect URL in case of exception or invalid input with Sping?

Time:10-19

I have a GET method inside a controller that get a lot of parameters. I want to redirect the URL in case of exception or invalid input and return (print to the client) the exception with addition message.

My function looks like this:

@GetMapping("/v1.0/hello/{userName}")
public ClientResponse getDetails(@PathVariable(value = "userName") String userName,
                                 @RequestParam(value = "expInp1", required = false) int expInp1,
                                 @RequestParam(value = "expInp2", required = false) int expInp2,
                                 @RequestParam(value = "expInp3", required = false) int expInp3){
    // do something...

    return clientResponse; 
}

ClientResponse is an object that contain all the relevant details and can't be changed.

For example, if someone inserts the following URL /v1.0/hello/{userName}?expInp4=XXX, I want to redirect them to /v1.0/hello/ with a suitable message.

Is there a Spring annotation doing that without a lot of code? And if not, what is the best way in my case?

CodePudding user response:

create a new class with @RestControllerAdvice or @ControllerAdvice annotation to handle the exception globally in Spring Boot.

Refer this link

CodePudding user response:

You can take a look at @RestControllerAdvice coupled with @ExceptionHandler annotation. you can follow these steps to create a redirect system:

  1. create your own exception

    public class RedirectException extends RuntimeException{
      private String redirectUrl;
    
      public RedirectException(String message, String rUrl) {
        super(message);
        this.redirectUrl = rUrl;
      }
    } 
    
  2. create your controller advice

    @RestControllerAdvice
    public class ErrorController {
      @ExceptionHandler(RedirectExecption.class)
      public void handleRedirect(RedirectException re, HttpServletResponse res) {
        res.sendRedirect(re.getRedirectUrl);
      }
    }
    
  3. when you want to send a redirect response in you running code just throw a redirectException with the redirecturl you want to reach

p.s. you can use the same mechanism for building an error handling system.

  • Related