[SpringBoot] REST API 예외 처리 (0821)

왕감자·2024년 8월 21일

KB IT's Your Life

목록 보기
139/177

try-catch

        try{
            throw new Exception("에러 보고싶어서 낸고얌");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "에러낫슴요";
        }


try-catch 안 쓰고 그냥 throw new Exception();~

throw Exception 추가 : 에러를 뱉을 수 있다는 경고문 같은 역할

String detail() throws Exception {
...
}

ResponseEntity

에러코드와 에러메세지를 보낼 수 있음
return 타입을 ResponseEntity<String> 으로~

    @GetMapping("/detail/{id}")
    ResponseEntity<String> detail(@PathVariable Long id, Model model) {

        try{
            throw new Exception("에러 보고싶어서 낸고얌");
        } catch (Exception e) {
            return ResponseEntity.status(에러코드).body("에러메세지");
        }
    }

에러코드

  • 유저 잘못 : 4XX
  • 서버 잘못 : 5XX
  • 정상 : 200

HttpStatus.에러이유

: 알맞은 에러코드로 바꿔줌

return ResponseEntity.status(HttpStatus.NOT_FOUND).body("에러메세지");

@ExceptionHandler

같은 클래스에서 발생하는 모든 에러 캐치
모든 에러를 캐치해주는 스프링 문법

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handler() {
   return ResponseEntity.status(400).body("에러!!!!!");
}

@ControllerAdvice

모든 Controller 파일의 에러를 캐치함

// MyExceptionHandler.java
@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handler() {
        return ResponseEntity.status(400).body("에러!!!!!");
    }
}

특정 에러만 실행

적절하게 @ExceptionHandler(예외) 넣어주면 됨

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResponseEntity<String> handler1() {
        return ResponseEntity.status(400).body("타입 틀린!!!! 에러!!!!!");
    }

    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handler2() {
        return ResponseEntity.status(400).body("에러!!!!!");
    }
}

0개의 댓글