springboot自定義錯誤頁面(轉)


方法一:Spring Boot 將所有的錯誤默認映射到/error, 實現ErrorController

@Controller
@RequestMapping(value = "error")
public class BaseErrorController implements ErrorController {
private static final Logger logger = LoggerFactory.getLogger(BaseErrorController.class);

@Override
public String getErrorPath() {
logger.info("出錯啦!進入自定義錯誤控制器");
return "error/error";
}

@RequestMapping
public String error() {
return getErrorPath();
}

}

方法二:添加自定義的錯誤頁面

2.1 html靜態頁面:在resources/public/error/ 下定義
如添加404頁面: resources/public/error/404.html頁面,中文注意頁面編碼
2.2 模板引擎頁面:在templates/error/下定義
如添加5xx頁面: templates/error/5xx.ftl
注:templates/error/ 這個的優先級比較 resources/public/error/高

方法三:使用注解@ControllerAdvice

/**
* 統一異常處理
*
* @param exception
* exception
* @return
*/

@ExceptionHandler({ RuntimeException.class })
@ResponseStatus(HttpStatus.OK)
public ModelAndView processException(RuntimeException exception) {
logger.info("自定義異常處理-RuntimeException");
ModelAndView m = new ModelAndView();
m.addObject("roncooException", exception.getMessage());
m.setViewName("error/500");
return m;
}

/**
* 統一異常處理
*
* @param exception
* exception
* @return
*/

@ExceptionHandler({ Exception.class })
@ResponseStatus(HttpStatus.OK)
public ModelAndView processException(Exception exception) {
logger.info("自定義異常處理-Exception");
ModelAndView m = new ModelAndView();
m.addObject("roncooException", exception.getMessage());
m.setViewName("error/500");
return m;
}
                                            <link rel="stylesheet" href="http://csdnimg.cn/release/phoenix/production/markdown_views-0bc64ada25.css">
                                </div>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM