iCodeLikeImDrunk
iCodeLikeImDrunk

Reputation: 17806

How to config/setup a redirect for all errors in Spring Boot?

Right now, all 404/500 results in a json error message.

How can I configure it so that on all 404/500 just redirect to a specific error page?

I've added the following to my initializer class:

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
    return container -> {
        container.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/errorpage"));
        container.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/errorpage"));
    };
}

But now it just redirects to a blank page...

Solution? I basically implemented the error controller and force all to redirect to errorpage. My errorpage is a jsp that lives right under WEB-INF/pages. Now is this correct?

@RestController
@RequestMapping("/errorpage")
public class SimpleErrorController implements ErrorController {

@Autowired
public SimpleErrorController(ErrorAttributes errorAttributes) {
    Assert.notNull(errorAttributes, "ErrorAttributes must not be null");
}

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

@RequestMapping(produces = {"text/html"})
public ModelAndView errorHtml(HttpServletRequest request, HttpServletResponse response) {
    response.setStatus(400);
    return new ModelAndView("errorpage");
}
}

Upvotes: 0

Views: 3555

Answers (1)

Andonaeus
Andonaeus

Reputation: 872

EDIT: You would likely need to remove your Bean definition for this to work, as I see you have added that after I have submitted my answer.

Add thymeleaf dependency to your pom:

        <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

Depending on your spring boot version, add one of the two to your application properties file:

error.whitelabel.enabled=false

or

server.error.whitelabel.enabled=false

Create /src/main/resources/templates folder.

Add a file called error.html to this folder with the html you wish to display.

What we've done is use the thymeleaf templating engine to consume the default error.html file, and told Spring Boot not to use its default whitelabel error page.

Upvotes: 1

Related Questions