配置springboot的error页面

  1. 转自:https://blog.csdn.net/qq_35489575/article/details/79052513

  2.   
  3. import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;  
  4. import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;  
  5. import org.springframework.boot.web.servlet.ErrorPage;  
  6. import org.springframework.context.annotation.Bean;  
  7. import org.springframework.context.annotation.Configuration;  
  8. import org.springframework.http.HttpStatus;  
  9.   
  10. /** 
  11.  * 错误页面的配置 
  12.  */  
  13. @Configuration  
  14. public class ErrorPagesConfig {  
  15.     @Bean   //此注解一定记住要加上,别忘记  
  16.     public EmbeddedServletContainerCustomizer containerCustomizer(){  
  17.         return new EmbeddedServletContainerCustomizer() {  
  18.             @Override  
  19.             public void customize(ConfigurableEmbeddedServletContainer container) {  
  20.                                                         //状态码               错误页面的存储路径  
  21.                 ErrorPage errorPage400 = new ErrorPage(HttpStatus.BAD_REQUEST, "/error-400.html");  
  22.                 ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/error-404.html");  
  23.                 ErrorPage errorPage500 = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error-500.html");  
  24. //...可自己一个一个的补全  
  25.                 container.addErrorPages(errorPage400,errorPage404,errorPage500);  
  26.             }  
  27.         };  
  28.     }  
  29. }  

如果你有自己设计一个错误编码和错误信息的Exception,定义为MyException extends RuntimeException,

哪里会出错throw MyException

然后配置一个Controller 

使用@ControllerAdvice做统一异常处理:

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(value = MyException.class)
    public String MyExceptionHandler(){
        return "error";

    }
}
如果要返回一些错误码和错误信息,你就加个Model model ,错误页面接收一下就行了。

你可能感兴趣的:(springboot)