1

I am trying to customize /error by implementing Error controller in a class annonated with RestController.

The Spring Boot app includes autoconfiguration Library and does not explicitly set or use MVC.

@RequestMapping("/error")
public String handler(){
return "Error Occurred";
}

The above code works fine when the error status is 401 and 404.

@RequestMapping("/error")
public void handler(HttpServletResponse response)
{
response.sendRedirect("http://<url>/home");
return;// edit: Even adding this statement is just setting location but not redirecting.
}

This is setting location in response with redirect url but not redirecting.

Requirement is to map the /error to external UI page.

Now, when I use, redirectview or responsentity, then, the logic in handler only works when /error is invoked manually and 404 is not invoking /error. It just says This page is not found. Can someone tell me is this because of autoconfiguration Library or am I missing anything?

2 Answers2

0
  1. Adding this entry to the application.properties file : server.error.whitelabel.enabled=false. This will disable the white label error page entirely.

  2. A Custom Error Controller :

     @RequestMapping("/error")
     public String handleError(HttpServletRequest request) {
     Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
    
     if (status != null) {
         Integer statusCode = Integer.valueOf(status.toString());
    
         if(statusCode == HttpStatus.NOT_FOUND.value()) {
             return "error-404";
         }
         else if(statusCode == HttpStatus.UNAUTHORIZED).value()) {
             return "error-401";
         }
     }
     return "error";
    

    }

You can add html pages for the respective errors.

Example : For a 404 error, User will see error-404.html page.

Try below in case you want to redirect to external UI :

String redirectUrl = `https://www.yahoo.com";
return "redirect:" + redirectUrl;
Amit kumar
  • 2,169
  • 10
  • 25
  • 36
0

Issue resolved. This application has some custom libraries which uses Spring Security. Without access token, this error is occuring. I need to explore more of 401 error but for now, to handle errors am using class with @RestControllerAdvice and set property spring.mvc.throw-exception-if-no-handler-found to true and also, disable whitelabel.

Redirection logic works when the Authorization is successful.