SpringBoot 통일 이상 처리 상세 설명
5808 단어 SpringBoot통일 하 다.예외 처리
pom 파일 설정
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>bsea</groupId>
<artifactId>SpringBootException</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.14.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
시작 클래스
package com.zz;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class,args);
}
}
사용자 정의 이상 클래스
package com.zz.exception;
public class UserNotExistException extends RuntimeException{
private static final long serialVersionUID = -1574716826948451793L;
private String id;
public UserNotExistException(String id){
super("user not exist");
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
통일 처리 류1.class 에@Controller Advice 를 추가 하면 전역 이상 처리 클래스 를 표시 합 니 다.
2.방법 에@ExceptionHandler(User NotExistException.class)를 추가 하면 catch 가 이 이상 유형 에 이 르 렀 음 을 나타 내 고 방법 에 따라 처리 할 수 있 습 니 다.서로 다른 이상 은 서로 다른 방법 으로 처리 할 수 있 습 니 다.모든 방법 에는 이 주석 괄호 안의 이상 류 를 통 해 처리 해 야 할 이상 유형 을 설정 합 니 다.
package com.zz.handler;
import com.zz.exception.UserNotExistException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class ControllerExceptionHandler {
// json
@ExceptionHandler(UserNotExistException.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Map<String, Object> handleUserNotExistsException(UserNotExistException e) {
Map<String, Object> map = new HashMap<>();
map.put("id", e.getId());
map.put("message", e.getMessage());
return map;
}
// ,
@ExceptionHandler(ArithmeticException.class)
public String handle1(ArithmeticException e) {
System.out.println("handle1 500* **************");
return "/500.html";
}
}
컨트롤 러 클래스
package com.zz.controller;
import com.zz.exception.UserNotExistException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/{id:\\d+}")
public void get(@PathVariable String id) {
throw new UserNotExistException(id);
}
@GetMapping("error2")
public void get2() {
int a=1/0;
}
}
\#실행 결과코드 주소 github:링크 설명 추가
위 에서 말 한 것 은 편집장 님 께 서 소개 해 주신 SpringBoot 통일 이상 처리 에 대한 상세 한 통합 입 니 다.여러분 께 도움 이 되 셨 으 면 합 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.