Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

208
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda