SpringBoot 利用thymeleaf自定義錯誤頁面
導(dǎo)入thymeleaf
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId></dependency>
自定義異常類
建立監(jiān)聽異常類
MyException.class
package com.example.demo.domain;public class MyException extends RuntimeException { private int code; private String msg; public MyException(int code, String msg) { this.code = code; this.msg = msg; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; }}
CustomExtHandle 監(jiān)測異常
package com.example.demo.domain;import org.slf4j.LoggerFactory;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RestControllerAdvice;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import java.util.HashMap;import java.util.Map;import java.util.logging.Logger;@RestControllerAdvicepublic class CustomExtHandle { // 捕獲全局異常 @ExceptionHandler(value = Exception.class) Object handleException(Exception e, HttpServletRequest request) { Map<String, Object> map = new HashMap<>(); map.put('code', 100); map.put('msg', e.getMessage()); map.put('url', request.getRequestURL()); return map; } // 如果是Myexception類 @ExceptionHandler(value = MyException.class) Object handleMyException(MyException e, HttpServletRequest request) { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName('error.html'); // 指定錯誤跳轉(zhuǎn)頁面 需要在templates里面新建 一個error.html modelAndView.addObject('msg', e.getMsg()); modelAndView.addObject('code', e.getCode()); modelAndView.addObject('url', request.getRequestURL()); return modelAndView;// 當(dāng)然這里也可以返回json數(shù)據(jù) 前后臺分離的話直接返回一個json即可 }}
template/error.html
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title></head><body><h1>出異常了</h1><span>錯誤信息:</span><h1 th:text='${msg}'></h1> // 獲取變量<span>錯誤狀態(tài)碼:</span><h1 th:text='$[code]'></h1><span>失敗API地址:</span><h1 th:text='${url}'></h1></body></html>
使用
@RequestMapping('/user_info') public Map<String, String> testMap() { throw new MyException(500, '手動拋出'); }
效果
以上就是SpringBoot 利用thymeleaf自定義錯誤頁面的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 自定義錯誤頁面的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. CSS hack用法案例詳解2. 利用promise及參數(shù)解構(gòu)封裝ajax請求的方法3. JSP數(shù)據(jù)交互實現(xiàn)過程解析4. asp(vbs)Rs.Open和Conn.Execute的詳解和區(qū)別及&H0001的說明5. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向6. Ajax實現(xiàn)表格中信息不刷新頁面進(jìn)行更新數(shù)據(jù)7. PHP設(shè)計模式中工廠模式深入詳解8. 解決AJAX返回狀態(tài)200沒有調(diào)用success的問題9. .NET中l(wèi)ambda表達(dá)式合并問題及解決方法10. ThinkPHP5實現(xiàn)JWT Token認(rèn)證的過程(親測可用)
