i am new in spring boot, i following the tuorial from Pluralsight.
i got problem by using exceptions
here is my service interface
package com.stev.pillecons.pilleCons.services;
import com.stev.pillecons.pilleCons.models.LePille;
import java.util.List;
public interface PilleService {
List<LePille> listPilles();
LePille findPille(Integer id);
}
here is how i implements the services
package com.stev.pillecons.pilleCons.services;
import com.stev.pillecons.pilleCons.exceptions.PilleException;
import com.stev.pillecons.pilleCons.models.LePille;
import com.stev.pillecons.pilleCons.repositories.LePilleRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class PilleServiceImpl implements PilleService{
@Autowired
private LePilleRepo pilleRepo;
@Override
public List<LePille> listPilles() {
return (List<LePille>) pilleRepo.findAll();
}
@Override
public LePille findPille(Integer id) {
Optional<LePille> optionalLePille = pilleRepo.findById(id);
if (optionalLePille.isPresent())
return optionalLePille.get();
else
return new PilleException("pille not found");
}
}
i got red under line to this line : return new PilleException("pille not found");
here is my exception
package com.stev.pillecons.pilleCons.exceptions;
public class PilleException extends RuntimeException {
public PilleException (String ex) {super(ex);}
}
EDIT
i use this code
@Override
public LePille findPille(Integer id) {
return pilleRepo.findById(id).orElseThrow(()-> new PilleException("pille not found"));
}
it works, why my code doesn't work ?
CodePudding user response:
An exception is not returned it is thrown.
throw new PilleException("pille not found");
CodePudding user response:
Simon is correct and one of the best practice to handle exceptions is using @ControllerAdvice and handle all @ExceptionHandlers from single point.