日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot默认的错误处理机制

發布時間:2023/12/13 javascript 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot默认的错误处理机制 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

錯誤處理機制:

訪問一個不存在的頁面時,或者程序拋出異常時

默認效果

  • 瀏覽器返回一個錯誤的頁面,注意查看瀏覽器發送請求的請求頭

  • 可以使用專業的軟件比如postman分析返回的json數據

springboot錯誤處理的自動配置信息

主要給日容器中注冊了以下組件:

  • ErrorPageCustomizer 系統出現錯誤以后來到error請求進行處理;相當于(web.xml注冊的錯誤頁面規則)
  • BasicErrorController 處理/error請求
  • DefaultErrorViewResolver 默認的錯誤視圖解析器
  • DefaultErrorAttributes 錯誤信息
  • defaultErrorView 默認錯誤視圖

@getErrorAttributes()返回的參數

  • timestamp:時間戳
  • status:狀態碼
  • error:錯誤提示
  • exception:異常對象
  • message:異常消息
  • errors:JSR303數據校驗的錯誤都在這里

2.0以后默認是不顯示exception的,需要在配置文件中開啟

server.error.include-exception=true

如何定制JSON數據

springboot做了自適應效果,瀏覽器訪問響應錯誤頁面。客戶端訪問響應錯誤信息的json數據

  • 第一種方法,定義全局異常處理器類注入到容器中,捕獲到異常返回json格式的數據

    @ControllerAdvice public class MyExceptionHandler {@ResponseBody@ExceptionHandler(Exception.class)public Map<String, Object> handleException(Exception e) {Map<String, Object> map = new HashMap(2);map.put("code", "100011");map.put("msg", e.getMessage());return map;} }
  • 由上面我們已經知道數據的來源是調用DefaultErrorAttributes的getErrorAttributes方法得到的,而這個DefaultErrorAttributes是在ErrorMvcAutoConfiguration配置類中注冊的,并且注冊之前會檢查容器中是否已經擁有 @Bean@ConditionalOnMissingBean(value = {ErrorAttributes.class},search = SearchStrategy.CURRENT)public DefaultErrorAttributes errorAttributes() {return new DefaultErrorAttributes(this.serverProperties.getError().isIncludeException());}
  • 所以我們可以只要實現ErrorAttributes接口或者繼承DefaultErrorAttrites類,然后注冊到容器中就行了

    @ControllerAdvice public class MyExceptionHandler {@ExceptionHandler(Exception.class)public String handleException(Exception e, HttpServletRequest request) {Map<String, Object> map = new HashMap(2);map.put("name", "hello");map.put("password", "123456");//設置狀態碼request.setAttribute("javax.servlet.error.status_code", 500);//把數據放到request域中request.setAttribute("ext", map);return "forward:/error";} } @Configuration public class MyMvcConfig implements WebMvcConfigurer {@Beanpublic DefaultErrorAttributes errorAttributes() {return new MyErrorAttributes();}class MyErrorAttributes extends DefaultErrorAttributes {@Overridepublic Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {//調用父類的方法獲取默認的數據Map<String, Object> map = new HashMap<>(super.getErrorAttributes(webRequest, includeStackTrace));//從request域從獲取到自定義數據Map<String, Object> ext = (Map<String, Object>) webRequest.getAttribute("ext", RequestAttributes.SCOPE_REQUEST);map.putAll(ext);return map;}}......

    ?

    總結

    以上是生活随笔為你收集整理的SpringBoot默认的错误处理机制的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。