Spring Boot에서 애플리케이션을 개발 중입니다. 예외를 처리하는 가장 좋은 방법이 무엇인지 궁금합니다. 그래서 다음은 내 코드입니다.
ExceptionHandler.java
나는 @ControllerAdvice
. 사용하기에 가장 좋은 것은 무엇입니까? @ControllerAdvice
또는 @RestControllerAdvice
?
@ControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(NotFoundException.class)
public ResponseEntity<ErrorResponse> notFound(NotFoundException notFoundException) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, notFoundException.getMessage());
return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
}
}
@Service
다음과 같이 서비스 계층 을 구현했습니다 .
@Override
public User update(User newUser) throws NotFoundException {
Optional<User> user = userRepository.findById(newUser.getId());
if (!user.isPresent()) throw new NotFoundException("Record Not Found!");
return userRepository.save(newUser);
}
에서 Controller.java
코드는 다음과 같다,
@PutMapping
public User update(@RequestBody User user) {
User updatedUser = userService.update(user);
if (updatedUser == null) throw new SomeOtherException("Exception while Updating!");
return updatedUser;
}
그래서 제 질문은
위의 접근 방식이 나쁜가요? 서비스 계층에서 예외를 throw해도 괜찮 @controlleradvice
습니까? 아니면 컨트롤러에만 던져야합니까? 예외를 처리하기위한 모범 사례를 찾고 있습니다. 누구든지 나를 도울 수 있습니까? 미리 감사드립니다.
당신이 사용한 방식은 완벽합니다.
마찬가지로 @ ControllerAdvice / @ RestControllerAdvice가 전역에 걸쳐 핸들 컨트롤러 예외로 사용된다 [흐름]가.
@Service layel에서도 예외를 던질 수 있습니다. [그것도 똑같습니다] ControllerAdvice가 그것을 잡을 것입니다.
자신 만의 방식으로 예외를 사용자 지정할 수 있습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다