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 통일 이상 처리 에 대한 상세 한 통합 입 니 다.여러분 께 도움 이 되 셨 으 면 합 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기