Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- 백준9012
- 이것이자바다9장
- 컴퓨터비전
- 백준스택
- 백준평범한배낭
- 백준10828
- BOJ
- 백준온라인저지
- 딥러닝
- 이것이자바다
- 코딩테스트실력진단
- 냅색알고리즘
- 확인문제
- 카카오코테
- 스파르타코딩클럽
- 가운데를말해요
- 백준
- 합성곱연산
- java
- 웹개발기초
- 백준가운데를말해요
- 2019카카오코테
- 코드트리
- 윤곽선검출
- 코테
- KT포트포워딩
- 이것이자바다확인문제
- BOJ1655
- 백준괄호
- 운영체제
Archives
- Today
- Total
코딩하는 락커
[Spring Boot를 이용한 RESTful Web Services 개발] 16강 본문
🍃 Spring/🌱 Spring Boot를 이용한 RESTful Web Service
[Spring Boot를 이용한 RESTful Web Services 개발] 16강
락꿈사 2022. 2. 7. 17:27예외 클래스 생성
- ExceptionResponse라는 Java 객체를 선언하여 예외 발생 시간, 예외 메시지, 상세정보 등 저장.
package com.example.restfulwebservice.exception;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExceptionResponse {
private Date timestamp;
private String message;
private String details;
}
일반적인 예외 클래스 생성
- ResponseEntityExceptionHandler 클래스를 상속받은 Handler 클래스 선언
- ResponseEntityExceptionHandler 클래스 : 시스템에서 에러 발생시 에러를 핸들링하기 위해 스프링에서 제공하는 클래스
- ControllerBean에서 예외 발생시 이 클래스가 발생하도록 설정
- AOP : 스프링 프레임워크에서 로깅 정보, 로그인 정보, 메시지 추가 정보 등 모든 비즈니스 로직을 수행하는 Controller에서 항상 실행시켜줘야 하는 공통적인 로직
- 스피링 부트 어플리케이션에서 공통적으로 처리 되어야 하는 로직, 메소드 등을 추가할 때 사용
- @RestController 어노테이션 추가하여 웹 서비스에서 사용할 수 있도록 함
- @ContollerAdvice 어노테이션 추가하여 모든 Controller가 실행될 때 반드시 이 어노테이션이 붙은 Bean이 실행되도록 함
package com.example.restfulwebservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.Date;
@RestController
@ControllerAdvice
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
// ResponseEntity는 사용자 객체 한명 추가했을 때 반환하는 형태의 값
// Exception ex는 메소드에서 발생했던 에러 객체
// WebRequest request는 어디서 발생했는지 알아보기 위한 request 정보
// @ExceptionHandler 어노테이션은 이 메소드가 ExceptionHandler로 사용될 수 있음을 지칭.
@ExceptionHandler(Exception.class)
public final ResponseEntity<Object> handlerAllException(Exception ex, WebRequest request){
// 발생 날짜, 에러 메시지, request의 부가적인 내용
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
// 위 값을 ResponseEntity의 인자로 넣어 반환
// 서버에서 발생하는 일반화 된 에러이기 때문에 HttpStatusCode는 500번이고 INTERNAL_SERVER_ERROR로 지정
return new ResponseEntity(exceptionResponse, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
존재하지 않는 사용자를 요청할 때 발생시킬 예외 클래스 생성
// @ExceptionHandler(UserNotFoundException.class)를 사용하여 사용자가 없을 때의 예외로 지정
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<Object> handleUserNotFound(Exception ex, WebRequest request){
// 발생 날짜, 에러 메시지, request의 부가적인 내용
ExceptionResponse exceptionResponse =
new ExceptionResponse(new Date(), ex.getMessage(), request.getDescription(false));
// 위 값을 ResponseEntity의 인자로 넣어 반환
// status code를 NotFound로 지정
return new ResponseEntity(exceptionResponse, HttpStatus.NOT_FOUND);
}
'🍃 Spring > 🌱 Spring Boot를 이용한 RESTful Web Service' 카테고리의 다른 글
[Spring Boot를 이용한 RESTful Web Services 개발] 18~19강 (0) | 2022.02.08 |
---|---|
[Spring Boot를 이용한 RESTful Web Services 개발] 17강 (0) | 2022.02.07 |
[Spring Boot를 이용한 RESTful Web Services 개발] 13~15강 (0) | 2022.02.06 |
[Spring Boot를 이용한 RESTful Web Services 개발] 11~12강 (0) | 2022.02.05 |
[Spring Boot를 이용한 RESTful Web Services 개발] 9~10강 (0) | 2022.02.05 |
Comments