スプリングは、複数の機能3を起動します.Spring Boot Exceptionの処理

7180 ワード

1.Exception処理

  • Webアプリケーションの観点から、エラーが発生した場合、エラーを低減できる方法は多くない
  • 1. エラーページ
  • 2. 4XX Error or 5XX Error
  • 3. クライアントが200以外のトランザクションを処理できない場合、200を削減し、追加のエラーメッセージ
  • を送信することができる.

    2.テスト項目

  • exception Spring initializerプロジェクト
  • の作成
  • Package : controller, dto
  • Class : RestApiController, User
  • 01.Errorの作成

  • User.java
  • @NotEmpty
  • Null値
  • は受け入れられません.
  • @Size(min = 1, max = 10)
  • 文字長
  • @Min(1)
  • ピーク
  • @NotNull
  • nullを除く
  • package com.example.exception.dto;
    
    import javax.validation.constraints.Min;
    import javax.validation.constraints.NotEmpty;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    
    public class User {
    
        @NotEmpty
        @Size(min = 1, max = 10)
        private String name;
    
        @Min(1)
        @NotNull
        private Integer age;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
  • RestApiController.java
  • @Valid
  • 入力オブジェクト検証チェック
  • を行う.
    package com.example.exception.controller;
    
    import com.example.exception.dto.User;
    import org.springframework.web.bind.annotation.*;
    
    import javax.validation.Valid;
    
    @RestController
    @RequestMapping("/api")
    public class RestApiController {
    
        @GetMapping("/user")
        public String get(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age) {
            User user = new User();
            user.setName(name);
            user.setAge(age);
    
            int a = 10 + age;
    
            return user.toString();
        }
    
        @PostMapping("/user")
        public User post(@Valid @RequestBody User user) {
            return user;
        }
    }






    02.エラー処理


    -1.グローバルコンサルティングの応用

  • Package : advice
  • Class : GlobalControllerAdvice
  • 1.完全異常処理

  • GlobalControllerAdvice.java
  • @RestControllerAdvice
  • RestControlの異常処理
  • @ExceptionHandler
  • @ExceptionHandler(value = Exception.class)
  • 値入力時に処理する異常
  • package com.example.exception.advice;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    @RestControllerAdvice
    public class GlobalControllerAdvice {
    
        // value = 내가 잡을 예외
        @ExceptionHandler(value = Exception.class)
        public ResponseEntity exception(Exception e) {
            System.out.println("------------------------------");
            System.out.println(e.getLocalizedMessage());
            System.out.println("------------------------------");
    
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
        }
    }



    -2.特定異常の処理

  • GlobalControllerAdvice.java
  • @ExceptionHandler(value = MethodArgumentNotValidException.class)
  • の値に特定の例外クラス
  • を入力.
    package com.example.exception.advice;
    
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestControllerAdvice;
    
    // (basePackages = "com. ...")로 예외처리할 패키지 지정 가능
    @RestControllerAdvice()
    public class GlobalControllerAdvice {
    
        // value = 내가 잡을 예외
        @ExceptionHandler(value = Exception.class)
        public ResponseEntity exception(Exception e) {
            System.out.println(e.getClass());
            System.out.println("------------------------------");
            System.out.println(e.getLocalizedMessage());
            System.out.println("------------------------------");
    
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
        }
    
        // 특정 메소드의 예외 처리
        @ExceptionHandler(value = MethodArgumentNotValidException.class)
        public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) {
    
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    -3.特定コントローラ内でのみ異常処理方法を使用

  • の異常処理方法を特定のコントローラに書き込むと、そのコントローラに作成された異常処理
  • のみが実行する.
  • RestApiCOntroller.java
  • package com.example.exception.controller;
    
    import com.example.exception.dto.User;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.*;
    
    import javax.validation.Valid;
    
    @RestController
    @RequestMapping("/api")
    public class RestApiController {
    
        @GetMapping("/user")
        public String get(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age) {
            User user = new User();
            user.setName(name);
            user.setAge(age);
    
            int a = 10 + age;
    
            return user.toString();
        }
    
        @PostMapping("/user")
        public User post(@Valid @RequestBody User user) {
            return user;
        }
    
        // 특정 메소드의 예외 처리
        @ExceptionHandler(value = MethodArgumentNotValidException.class)
        public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e) {
            System.out.println("rest api conroller");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }