Springboot exception redirection

goodlook0123 2022-02-13 08:17:04 阅读数:864

springboot exception redirection

        Recently, due to project use vue, Fore and aft end separation , When refreshing the page, it will vue The route is used as the service address to request, resulting in 404 error . Solid needs to be done 404 Exception redirection .

stay springboot 1.x Add the following code to the startup class during version , encounter 404 The error is redirected to index.html page

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {
return (container -> {
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
container.addErrorPages(error404Page);
});
}

But in springboot2.X There is no time for EmbeddedServletContainerCustomizer class , use tomcat Instead of ,

Therefore, we need to deal with exceptions in another way , Redirect to index.html

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
/**
* Abnormal forwarding
*/
@Component
public class ErrorConfig implements ErrorPageRegistrar {
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
ErrorPage error400Page = new ErrorPage(HttpStatus.BAD_REQUEST, "/index.html");
ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error401Page");
ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error500Page");
registry.addErrorPages(error400Page,error401Page,error404Page,error500Page);
}
}

 

copyright:author[goodlook0123],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/02/202202130817022847.html