>  기사  >  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 파일에 properties 설정

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

c, 백그라운드 처리 핸들러

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 작성, 배경 예외 인쇄

------------기본 오류
2017-06-16 14:54:05.314 WARN 6892 --- [nio-8080-exec-1] 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으로 문의하세요.