Spring

[스프링] Exception 처리하는 방법

웨일파도 2023. 7. 5. 15:58
반응형

Spring에서 Exception처리하는 방법

1. @ControllerAdvice: Global 예외 처리 및 특정 package / controller 예외처리 가능
2. @ExceptionHandler: 특정 controller 예외처리 가능

 

 

@ExceptionHandler

 

[컨트롤러 어드바이스(ContorllerAdvice) 에서 에러 처리]

package com.example.practice3.spring_exception.advice;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


@RestControllerAdvice
public class ApiControllerAdvice {
    @ExceptionHandler(value = Exception.class)
    public ResponseEntity exception(Exception e) {
        System.out.println(e.getClass().getName());
        System.out.println("에러 발생 이유 : " + e.getLocalizedMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("에러 발생");
    }

    @ExceptionHandler(value = ArithmeticException.class)
    public ResponseEntity arthmeticsException(ArithmeticException ae) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("0을 나누는 시도를 하였습니다.");
    }

    @ExceptionHandler(value = NullPointerException.class)
    public ResponseEntity nullPointerException(NullPointerException npe) {
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("내부에서 객체를 생성하지 않아서 오류 발생하였습니다.");

    }
}

  • 0 을 나누는 에러 

  • 내부에 객체 미생성

반응형