Как лучше всего обрабатывать исключения в Spring Boot?JAVA

Программисты JAVA общаются здесь
Гость
Как лучше всего обрабатывать исключения в Spring Boot?

Сообщение Гость »


Я разрабатываю приложение в Spring Boot. Мне было интересно, как лучше всего обрабатывать исключения. Итак, вот мой код:

Код: Выделить всё

ExceptionHandler.java
Я использую @ControllerAdvice. Что лучше всего использовать? @ControllerAdvice или @RestControllerAdvice?

Код: Выделить всё

@ControllerAdvice
public class ExceptionHandler {

@ExceptionHandler(NotFoundException.class)
public ResponseEntity notFound(NotFoundException notFoundException) {
ErrorResponse errorResponse = new ErrorResponse(HttpStatus.NOT_FOUND, notFoundException.getMessage());
return new ResponseEntity(errorResponse, HttpStatus.NOT_FOUND);
}
}
И реализовали уровень сервиса @Service следующим образом:

Код: Выделить всё

@Override
public User update(User newUser) throws NotFoundException {
Optional 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;
}
So my questions are:
Is the above approach bad? Is it okay to throw exceptions in the service layer and will it catch automatically by @controlleradvice? Or need to throw only in the controller? I am seeking the best practice to handle exceptions.


Источник: https://stackoverflow.com/questions/647 ... pring-boot

Вернуться в «JAVA»