반응형
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 을 나누는 에러
- 내부에 객체 미생성
반응형
'Spring' 카테고리의 다른 글
[스프링] @PathVariable, @RequestParam (0) | 2023.07.06 |
---|---|
[스프링] 예외처리 @ExceptionHandler (0) | 2023.07.05 |
[스프링] 검증 : annotation 생성 (0) | 2023.07.05 |
[스프링] 검증 : @validated @RequestParam (0) | 2023.07.05 |
[스프링] 검증 : bindingResult (0) | 2023.07.05 |