1. 程式人生 > >SpringBoot學習11:springboot異常處理方式1(自定義異常頁面)

SpringBoot學習11:springboot異常處理方式1(自定義異常頁面)

發生 title temp boot public main pan 頁面 exce

SpringBoot 默認的處理異常的機制:SpringBoot 默認的已經提供了一套處理異常的機制。一旦程序中出現了異常 SpringBoot 會向/error 的 url 發送請求。在 springBoot 中提供了一個叫 BasicExceptionController 來處理/error 請求,然後跳轉到默認顯示異常的頁面來展示異常信息。

技術分享圖片

如 果 我 們 需 要 將 所 有 的 異 常 同 一 跳 轉 到 自 定 義 的 錯 誤 頁 面 , 需 要 在src/main/resources/templates 目錄下創建 error.html 頁面。註意:名稱必須叫 error

自定義錯誤頁面

<!
DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>自定義錯誤頁面</title> </head> <body> 頁面出錯了。。。請與管理員聯系 <span th:text="${message}"></span> <!--發生錯誤的信息--> <span th:text="${error}"
></span> </body> </html>

編寫controller

package com.bjsxt.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by Administrator on 2019/2/12.
 */
@Controller
public class IndexController {


    @RequestMapping(
"toIndex") public String toIndex(){ String str=null; str.length(); return "index"; } @RequestMapping("toIndex2") public String toIndex2(){ int num=10/0; return "index"; } }

技術分享圖片

SpringBoot學習11:springboot異常處理方式1(自定義異常頁面)