Я разрабатываю приложение в Spring Boot. Мне было интересно, как лучше всего обрабатывать исключения. Итак, вот мой код:
Код: Выделить всё
ExceptionHandler.javaКод: Выделить всё
@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);
}
}
Код: Выделить всё
@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);
}
Код: Выделить всё
@PutMapping
public User update(@RequestBody User user) {
User updatedUser = userService.update(user);
if (updatedUser == null) throw new SomeOtherException("Exception while Updating!");
return updatedUser;
}
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