SpringBoot 利用thymeleaf自定義錯(cuò)誤頁(yè)面
導(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)測(cè)異常
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'); // 指定錯(cuò)誤跳轉(zhuǎn)頁(yè)面 需要在templates里面新建 一個(gè)error.html modelAndView.addObject('msg', e.getMsg()); modelAndView.addObject('code', e.getCode()); modelAndView.addObject('url', request.getRequestURL()); return modelAndView;// 當(dāng)然這里也可以返回json數(shù)據(jù) 前后臺(tái)分離的話直接返回一個(gè)json即可 }}
template/error.html
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title></head><body><h1>出異常了</h1><span>錯(cuò)誤信息:</span><h1 th:text='${msg}'></h1> // 獲取變量<span>錯(cuò)誤狀態(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, '手動(dòng)拋出'); }
效果
以上就是SpringBoot 利用thymeleaf自定義錯(cuò)誤頁(yè)面的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot 自定義錯(cuò)誤頁(yè)面的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python編寫nmap掃描工具2. PHP設(shè)計(jì)模式(四)原型模式Prototype實(shí)例詳解【創(chuàng)建型】3. python 爬取嗶哩嗶哩up主信息和投稿視頻4. PHP擴(kuò)展之APC——Alternative PHP Cache(可選PHP緩存)5. ASP.NET MVC前臺(tái)動(dòng)態(tài)添加文本框并在后臺(tái)使用FormCollection接收值6. 如何基于python3和Vue實(shí)現(xiàn)AES數(shù)據(jù)加密7. 10個(gè)提供免費(fèi)PHP腳本下載的網(wǎng)站8. Java向Runnable線程傳遞參數(shù)方法實(shí)例解析9. Java 基于UDP協(xié)議實(shí)現(xiàn)消息發(fā)送10. php5.6不能擴(kuò)展redis.so的解決方法
