• 로그인
  • 장바구니에 상품이 없습니다.

home2 게시판 Spring 게시판 예외 처리 질문있습니다

예외 처리 질문있습니다

4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 글쓴이
  • #128580

    이재륜
    참가자
    package com.ryun.shop;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
    @ControllerAdvice
    public class MyExceptionHandler {
        @ExceptionHandler(MethodArgumentTypeMismatchException.class)
        public ResponseEntity<String> handler1(){
            return ResponseEntity.status(400).body("에러남");
        }
        @ExceptionHandler(Exception.class)
        public ResponseEntity<String> handler(){
            return ResponseEntity.status(400).body("에러남");
        }
    }
    다음과 같이 기존에 있는 MyExceptionHandler를 지우지 않고 
    @PostMapping("/modify")
        String modifyItem(@RequestParam Long id, @RequestParam String title, @RequestParam Integer price) throws Exception{
            itemService.modifyItem(id,title,price);
            return "redirect:/list";
        }
    
    
    public void modifyItem(Long id, String title, Integer price) throws Exception{
        Item item = new Item();
        item.setId(id);
        item.setTitle(title);
        item.setPrice(price);
        if (item.getTitle().length()>=100 || item.getPrice()<0){
            throw new Exception("가격은 0이상, 제목은 100자 미만으로 만드세요");
        } else {
            itemRepository.save(item);
        }
    }
    
    다음과 같은 modifyItem 메소드에서 예외 발생시 가격은 0이상, 제목은 100자 미만으로 만드세요라는 제가 지정한 에러메세지를 출력하고 싶은데
    어떻게 하면 할 수 있을지 여쭤보고 싶습니다.
    #128589

    codingapple
    키 마스터
    함수안에 handler(Exception exception) 파라미터 추가하면 에러메세지와 내용같은거 들어있을걸요
    #128623

    이재륜
    참가자
    public class InvalidItemException extends Exception {
        public InvalidItemException(String message) {
            super(message);
        }
    } 이렇게 InvalidItemException클래스를 만들어 상속을 이용해서 되도록했는데 
    이렇게하는거 괜찮은 방법일까요?
    #128627

    codingapple
    키 마스터
    네 exception 종류 직접 만들어쓰기도 합니다
4 글 보임 - 1 에서 4 까지 (총 4 중에서)
  • 답변은 로그인 후 가능합니다.

About

현재 월 700명 신규수강중입니다.

  (09:00~20:00) 빠른 상담은 카톡 플러스친구 코딩애플 (링크)
  admin@codingapple.com
  이용약관
ⓒ Codingapple, 강의 예제, 영상 복제 금지
top

© Codingapple, All rights reserved. 슈퍼로켓 에듀케이션 / 서울특별시 강동구 고덕로 19길 30 / 사업자등록번호 : 212-26-14752 온라인 교육학원업 / 통신판매업신고번호 : 제 2017-서울강동-0002 호 / 개인정보관리자 : 박종흠