λ³Έλ¬Έ λ°”λ‘œκ°€κΈ°

SpringπŸƒ

Spring Exception

728x90

좜처 : 내일배움캠프

 

Http μƒνƒœμ½”λ“œλ„ Http 응닡 헀더 첫 쀄에 μΆ”κ°€λ˜μ–΄ λ°˜ν™˜λ˜λŠ” μš”μ†Œ 쀑 ν•˜λ‚˜μ΄λ‹€.

https://ryanclaire.blogspot.com/2020/10/HTTP-Overview.html

 

HTTP ν”„λ‘œν† μ½œ ꡬ쑰 κ°œμš”μ™€ 예제

HTTP ν”„λ‘œν† μ½œ ꡬ쑰 κ°œμš”μ™€ 예제

ryanclaire.blogspot.com

μ£Όμš” μ‘λ‹΅μƒνƒœμ½”λ“œ μ’…λ₯˜

200λ²ˆλŒ€ : 성곡

400λ²ˆλŒ€ : ν΄λΌμ΄μ–ΈνŠΈ μ—λŸ¬, 잘λͺ»λœ μš”μ²­

500λ²ˆλŒ€ : μ„œλ²„ μ—λŸ¬, μš”μ²­μ€ μ •ν™•ν•˜μ§€λ§Œ μ„œλ²„ μ—λŸ¬λ‘œ 였λ₯˜ λ°œμƒ

 

μŠ€ν”„λ§μ—μ„œ μ œκ³΅ν•˜λŠ” μƒνƒœμ½”λ“œ 정보 enum 클래슀

public enum HttpStatus {
	// 1xx Informational
	CONTINUE(100, Series.INFORMATIONAL, "Continue"),
	// ...

	// 2xx Success
	OK(200, Series.SUCCESSFUL, "OK"),
	CREATED(201, Series.SUCCESSFUL, "Created"),
	// ...

	// 3xx Redirection
	MULTIPLE_CHOICES(300, Series.REDIRECTION, "Multiple Choices"),
	MOVED_PERMANENTLY(301, Series.REDIRECTION, "Moved Permanently"),
	FOUND(302, Series.REDIRECTION, "Found"),
	// ...

	// --- 4xx Client Error ---
	BAD_REQUEST(400, Series.CLIENT_ERROR, "Bad Request"),
	UNAUTHORIZED(401, Series.CLIENT_ERROR, "Unauthorized"),
	PAYMENT_REQUIRED(402, Series.CLIENT_ERROR, "Payment Required"),
	FORBIDDEN(403, Series.CLIENT_ERROR, "Forbidden"),
	// ...
	

	// --- 5xx Server Error ---
	INTERNAL_SERVER_ERROR(500, Series.SERVER_ERROR, "Internal Server Error"),
	NOT_IMPLEMENTED(501, Series.SERVER_ERROR, "Not Implemented"),
	BAD_GATEWAY(502, Series.SERVER_ERROR, "Bad Gateway"),
	// ...

 

헀더

1. 응닡 본문이 Html인 경우

Content type: text/html

2. 응닡 본문이 Json인 경우

Content type: application/json

λ³Έλ¬Έ

1. Html

<!DOCTYPE html>
<html>
  <head><title>By @ResponseBody</title></head>
   <body>Hello, Spring μ •μ  μ›Ή νŽ˜μ΄μ§€!!</body>
</html>

2. Json


  "name":"홍길동",
  "age": 20
}

 

μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό μ œλŒ€λ‘œ ν•˜μ§€ λͺ»ν•œλ‹€λ©΄, μ‚¬μš©μžμ˜ 잘λͺ»λœ μš”μ²­μœΌλ‘œ μΈν•œ μ˜ˆμ™Έμ—λ„ 400 μ—λŸ¬κ°€ μ•„λ‹Œ 500 μ—λŸ¬κ°€ λ°œμƒν•  수 μžˆλ‹€.

μ‚¬μš©λ˜λŠ” κΈ°λŠ₯ : Exception Handler

 

-> μŠ€ν”„λ§ μ˜ˆμ™Έμ²˜λ¦¬ 방법

1) Controller μ½”λ“œ μˆ˜μ •

ResponseEntity 클래슀 μ‚¬μš© : Http response objectλ₯Ό μœ„ν•œ Wrapper 클래슀 ~ Http statusCode, Http headers, Http bodyλ₯Ό λ‹΄μ•„ μ‘λ‹΅ν•˜λŠ” 클래슀

@PostMapping("/folders")
    public ResponseEntity addFolders(
            @RequestBody FolderRequestDto folderRequestDto,
            @AuthenticationPrincipal UserDetailsImpl userDetails
            ) {
                try {
                    List<String> folderNames = folderRequestDto.getFolderNames();
                    User user = userDetails.getUser();

                    List<Folder> folders = folderService.addFolders(folderNames, user.getUsername());
                    return new ResponseEntity(folders, HttpStatus.OK);
                } catch (IllegalArgumentException ex) {
                    RestApiException restApiException = new RestApiException();
                    restApiException.setHttpStatus(HttpStatus.BAD_REQUEST);
                    restApiException.setErrorMessage(ex.getMessage());
                    return new ResponseEntity(
                            // Http Body
                            restApiException,
                            // Http StatusCode
                            HttpStatus.BAD_REQUEST);
                }
    }

Try - catch λ¬Έμ—μ„œ μš”μ²­μ΄ μ„±κ³΅ν–ˆμ„ κ²½μš°μ™€ 그렇지 λͺ»ν•  경우λ₯Ό λ‚˜λˆ„κ³  각각 κ·Έ 값을 ResponseEntity 객체둜 λ°˜ν™˜ν•œλ‹€.

 

2) @ExceptionHandler μ‚¬μš©

-> FolderController 클래슀 μ•ˆμ˜ λͺ¨λ“  λ©”μ„œλ“œμ— μ˜ˆμ™Έμ²˜λ¦¬λ₯Ό μ μš©ν•˜λŠ” 방법(AOP)

@ExceptionHandler({ IllegalArgumentException.class })
public ResponseEntity handleException(IllegalArgumentException ex) {
    RestApiException restApiException = new RestApiException();
    restApiException.setHttpStatus(HttpStatus.BAD_REQUEST);
    restApiException.setErrorMessage(ex.getMessage());
    return new ResponseEntity(
            // HTTP body
            restApiException,
            // HTTP status code
            HttpStatus.BAD_REQUEST
    );
}

1) 2) λͺ¨λ‘ 일일히 μΆ”κ°€ν•΄μ•Όν•˜κΈ° λ•Œλ¬Έμ— λ²ˆκ±°λ‘œμ›€μ΄ 크닀.

 

-> 방법은 λ‹€λ₯΄μ§€λ§Œ, μ˜ˆμ™Έλ₯Ό μ²˜λ¦¬ν•˜λŠ” λ…Όλ¦¬λŠ” κ°™λ‹€ : μ˜ˆμ™Έκ°€ μ˜ˆμƒλ˜λŠ” λΆ€λΆ„μ—μ„œ μ˜ˆμ™Έλ₯Ό λ§Œλ“€μ–΄ λ˜μ§€κ³ , κ·Έ μ˜ˆμ™Έλ‚΄μš©μ„ λ‹΄μ•„

ν΄λΌμ΄μ–ΈνŠΈμ— 보내기

~ κΈ€λ‘œλ²Œ μ˜ˆμ™Έ 처리

@ControllerAdvice μ‚¬μš© : μ€‘κ°„μ—μ„œ μš”μ²­μ„ 기닀리닀가 μ˜ˆμ™Έκ°€ λ°œμƒν•œ 경우 μ€‘κ°„μ—μ„œ μž‘μ•„μ±ˆ ν›„ μ˜ˆμ™Έμ²˜λ¦¬

@RestControllerAdvice

-> @ControllerAdvice + @ResponseBody

 

@RestControllerAdvice 적용

 

핡심 : 관심사λ₯Ό λΆ„λ¦¬ν•˜μž

728x90

'SpringπŸƒ' μΉ΄ν…Œκ³ λ¦¬μ˜ λ‹€λ₯Έ κΈ€

데이터 베이슀λ₯Ό 더 μ•ˆμ „ν•˜κ²Œ κ΄€λ¦¬ν•˜κΈ°(Primary, Replica)  (0) 2022.12.29
Spring Transaction  (0) 2022.12.29
Spring AOP  (0) 2022.12.28
ν…ŒμŠ€νŠΈ μ½”λ“œ  (0) 2022.12.27
OAuth2  (0) 2022.12.27