Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

211
Visualizações
I want to return a Exception while my return type is Dto

If I couldn't find a user in my db with given id. I want to return an exception instead of null Dto, how can I do this?

public UserDto updateUser(Long id, UserDto userDto) {

    UserDto userDtoNew = null;

    if (userRepository.findById(id).isPresent()) {

        User existingUser = userRepository.findById(id).get();
        existingUser.setPassword(userDto.getPassword());
        existingUser.setUserName(userDto.getUserName());
        userDtoNew = userMapper.toDto(existingUser);

        return userDtoNew;
    }

    return userDtoNew;

}
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

This is a terrible way to use a an Optional. Please learn how to properly use it.

return userRepository.findById(id)
 .map(it -> {
    it.setPassword(userDto.getPassword());
    it.setUserName(userDto.getUserName());
  }).map(userMapper::toDto)
  .orElseThrow(() -> new IllegalArgumentException("No user found for " + id));

Something along those lines is how to properly use an Optional and to throw an exception if nothing is found.

Ideally the thing called inside the map function/method is just a oneliner. So instead of having the code block with {} you might want to move that to a method to make it more readable.

private User update(User user, UserDto userDto) {
  user.setPassword(userDto.getPassword());
  user.setUserName(userDto.getUserName());
  return user;
}
return userRepository.findById(id)
 .map(it -> update(it, userDto))
 .map(userMapper::toDto)
 .orElseThrow(() -> new IllegalArgumentException("No user found for " + id));
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda