【後端】如何定製自己的錯誤介面(瀏覽器)
阿新 • • 發佈:2021-01-24
1.新建一個異常處理類
package com.atguigu.springboot.exception;
public class UserNotExistException extends RuntimeException{
private void supper(String 使用者不存在) {
}
public UserNotExistException() {
supper("使用者不存在");
}
}
2.在控制器中設定錯誤丟擲(自動識別是瀏覽器還是客戶端)
@ResponseBody
@RequestMapping( "/hello")
public String HelloWorld(@RequestParam("user") String user){
if(user.equals("aaa")){
throw new UserNotExistException();
}
return "Hello World";
}
3.當發生錯誤時,瀏覽器會自動識別要載入的頁面(如果沒有自己的頁面,瀏覽器就用預設頁面)。
- 自己頁面命名規則:【將錯誤頁面命名為 錯誤狀態碼.html 放在模板引擎資料夾裡面的 error資料夾下】,發生此狀態碼的錯誤就會來到 對應的頁面;
- 我們可以使用4xx和5xx作為錯誤頁面的檔名來匹配這種型別的所有錯誤,精確優先(優先尋找精確的狀態 碼.html); 頁面能獲取的資訊; timestamp:時間戳
status:狀態碼
error:錯誤提示
exception:異常物件
message:異常訊息
errors:JSR303資料校驗的錯誤都在這裡
1)、沒有模板引擎(模板引擎找不到這個錯誤頁面),靜態資原始檔夾下找;
2)、以上都沒有錯誤頁面,就是預設來到SpringBoot預設的錯誤提示頁面;
<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4" >
<h1>status:[[${status}]]</h1>
<h2>timestamp:[[${timestamp}]]</h2>>
<h2>exception:[[${exception}]]</h2>>
<h2>message:[[${message}]]</h2>>
</main>
頁面會顯示以上資訊,其中message部分會顯示super()中的內容