반응형
Web Application의 입장에서 바라보았을때, 에러가 났을 때 내려줄 수 있는 방법은 많지 않다.
1. 에러 페이지
2. 4XX Error or 5XX Error
3. Client가 200 외에 처리를 하지 못 할 때는 200을 내려주고 별도의 에러 Message 전달
@ControllerAdvice | Global 예외 처리 및 특정 package / Controller 예외 처리 |
@ExceptionHandler | 특정 Controller의 예외처리 |
전체 시스템에서 예외 처리를 하는 방법
dto 작성
package com.example.exception.dto;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
@NotEmpty
@Size(min = 1, max = 100)
private String name;
@Min(1)
@NotNull
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
Controller 작성
package com.example.exception.controller;
import com.example.exception.dto.User;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/user")
public class ApiController {
@GetMapping("")
// required = false -> 해당 파라미터가 입력안되어도 정상 처리되도록 설정
public User get(@RequestParam(required = false) String name, @RequestParam(required = false) Integer age){
User user = new User();
user.setName(name);
user.setAge(age);
int a = 10 + age;
return user;
}
@PostMapping("")
public User post(@Valid @RequestBody User user){
System.out.println(user);
return user;
}
}
전체 시스템에서 예외처리를 실행할 클래서 작성
package com.example.exception.advice;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
// 예외 처리를 담당할 controller 작성
// @RestControllerAdvice: @RestController를 담당하기 때문에
@RestControllerAdvice
public class GlobalControllerAdvice {
// 어떤에러를 잡을지 설정 -> 모든 에러
@ExceptionHandler(value = Exception.class)
public ResponseEntity exception(Exception e){
// 어느쪽이 잘못되었는지 확인
System.out.println(e.getClass().getName());
// 에러값을 받아올 수 있다.
System.out.println("===========================");
System.out.println(e.getLocalizedMessage());
System.out.println("===========================");
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("");
}
// 특정 에러를 잡도록 설정
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
오류 확인
특정 Controller 내부에서 에러 예외처리하는 방법
해당 Controller에 아래 코드를 추가한다.
// 우선순위는 RestController가 높기 때문에 여기서 예외 처리가 된다.
// 특정 에러를 잡도록 설정
@ExceptionHandler(value = MethodArgumentNotValidException.class)
public ResponseEntity methodArgumentNotValidException(MethodArgumentNotValidException e){
System.out.println("api controller");
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
양쪽 모두 적용할 경우 Controller 내부에 적용한 예외처리가 동작하고 나머지는 건너 뛰게 된다.
반응형
'Spring' 카테고리의 다른 글
Server to Server의 연결 - post (0) | 2021.06.26 |
---|---|
Server to Server의 연결 - get (0) | 2021.06.26 |
Custom Validation (0) | 2021.06.19 |
Validation (0) | 2021.06.19 |
Json으로 출력된 데이터 확인 (0) | 2021.06.13 |