기능이상이란
Java 및 Spring Boot 애플리케이션이 예상대로 동작하지 않는 경우를 말한다
버그, 예외 처리 미흡, 잘못된 비즈니스 로직 등이 원인이 될 수 있으며
아래는 가장 빈번하게 발생하는 NullPointerException에 대한 기능이상 예제이다
userService.getUserById(id)가 null을 반환하면 NullPointerException 발생
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public ResponseEntity<User> getUser(@PathVariable Long id) {
User user = userService.getUserById(id);
return ResponseEntity.ok(user); //user가 null이면 NullPointerException 발생 가능
}
}
Java8부터는
Optional을 사용하여 null 예외를 방지하고, 적절한 HTTP 응답 코드 반환하여
기능이상을 예방할 수 있다
@GetMapping("/{id}")
public ResponseEntity<?> getUser(@PathVariable Long id) {
return userService.getUserById(id)
.map(user -> ResponseEntity.ok(user))
.orElse(ResponseEntity.status(HttpStatus.NOT_FOUND).body("User not found"));
}
'Etc' 카테고리의 다른 글
BE개발자가 모르면 안되는 것 - 정보 누출 (0) | 2025.04.06 |
---|---|
개발자가 알아야 할 HTTP 헤더 5가지 (0) | 2025.04.06 |
인터페이스가 필요한가? (0) | 2025.03.30 |
BE개발자가 모르면 안되는 것 - SQL Injection (0) | 2025.03.23 |
[DB]파티션테이블 DELETE (0) | 2025.03.23 |