1

I created a custom error page to replace the default whitelabel based on this tutorial. It worked fine but I need to pass other attributes to the page so I changed my code to intercept the error endpoint based on the geoand's answer here.

Here is my final code:

@Controller
public class ErroHandlerController implements ErrorController {

    @Value("${terena.midas.location}")
    private String midasLocation;   

    @RequestMapping("/error")
    public String handleError( Model model ) {
        model.addAttribute( "midasLocation", midasLocation );
        return "error";
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }   

}

Well the code worked sending my variable midasLocation but I lost the error details like path, status,message, etc... How can I bring them back again?

Magno C
  • 1,922
  • 4
  • 28
  • 53

1 Answers1

1

You need to use the ErrorAttributes which "provides access to error attributes which can be logged or presented to the user".

Take a look:

Basic functionality:

import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.context.request.WebRequest;

@Controller
public class ErrorHandler implements ErrorController {

   private final ErrorAttributes errorAttributes;

   public ErrorHandler(ErrorAttributes errorAttributes) {
      this.errorAttributes = errorAttributes;
   }

   @GetMapping("/error")
   public String handleError(Model model, WebRequest webRequest) {
      model.addAttribute("midasLocation", "xxx");
      final Throwable error = errorAttributes.getError(webRequest);
      model.addAttribute("exception", error);
      model.addAttribute("message", error == null ? "" : error.getMessage());
      return "error";
   }

   @Override public String getErrorPath() {
      return "/error";
   }

   @GetMapping("/throwErrorForTest")
   public String throwError() {
      throw new RuntimeException("my exception");
   }
}
Andrei Damian-Fekete
  • 1,820
  • 21
  • 27
  • @Magno C, Spring recommends to use constructor injection (e.g. [Oliver Gierke - Why field injection is evil](http://olivergierke.de/2013/11/why-field-injection-is-evil/)). In unit tests you may need to use field injection. – Andrei Damian-Fekete Jul 14 '18 at 06:45
  • Annotate your constructor with @Autowired (although it should work without). The code I‘ve posted works with Spring Boot 2, you may have another setup. – Andrei Damian-Fekete Jul 15 '18 at 10:17
  • Yeah. I must agree. Very good points to consider in post you linked. Thanks. Its good to learn something new. – Magno C Jul 15 '18 at 15:42