首頁  >  文章  >  Java  >  java之Spring Boot全域異常處理實例詳解

java之Spring Boot全域異常處理實例詳解

怪我咯
怪我咯原創
2017-06-30 10:55:532356瀏覽

這篇文章主要為大家詳細介紹了Spring Boot全局異常處理的相關資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文為大家分享了Spring Boot全域異常處理,供大家參考,具體內容如下

1、後台處理異常

a、引入thymeleaf依賴

<!-- thymeleaf模板插件 -->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

b、在application.properties檔案中設定屬性

#关闭thymeleaf模板的缓存
spring.thymeleaf.cache=false

c、寫後台處理Handler  

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler {

  //设置此handler处理所有异常
 @ExceptionHandler(value=Exception.class)
 public void defaultErrorHandler(){
 System.out.println("-------------default error");
 }
}

d、背景異常列印

#-------------default error
2017-06-16 14:54:05.314  WARN 6892 --- [nio-8080-exec- 1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.dao.IncorrectResultSizeDataAccessException: result return#eperss more than one . ult returns more than one elements

2、頁面處理例外狀況

a、寫html範本頁面 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org" 
  xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<meta charset="UTF-8" />
<title>Insert title here</title>
</head>
<body>
 <h1 th:inlines="text">异常出现啦</h1>
 ${messages}
</body>
</html>

b、修改Handler

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
public class GlobalExceptionHandler {

 @ExceptionHandler(value=Exception.class)
 @ResponseBody
 public String defaultErrorHandler(){
  System.out.println("-------------default error");
  return "系统错误,请联系管理员";
 }
}

# c、頁面存取結果

#

以上是java之Spring Boot全域異常處理實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn