Spring capture and errors

Asked

Viewed 46 times

0

next...

I’m using spring for a particular project and wanted to know how to best capture errors.

have my Repository classes:

@Repository
public class PrimeiraClasseDaoImpl implements PrimeiraClasseDao {

    @PersistenceContext
    private EntityManager em;

    public void salvarObjeto(final ObjetoTeste objetoTeste) {
        em.persist(objetoTeste);    
    }

... outros métodos....

@Repository
public class SegundaClasseDaoImpl implements SegundaClasseDao {

    @PersistenceContext
    private EntityManager em;

    public void salvarObjeto(final ObjetoTeste objetoTeste) {
        em.persist(objetoTeste);    
    }

... outros métodos....

I also have the service class:

@Service
@Transactional
public class PrimeiraClasseServiceImpl implements PrimeiraClasseService {

    @Autowired
    private PrimeiraClasseDao primeiraClasseDao;

    @Autowired
    private SegundaClasseDao segundaClasseDao;

    public void salvarObjeto(PrimeiraClasse primeiraClasse) {

        segundaClasseDao.salvarObjeto(primeiraClasse.getSegundaClasse());
        primeiraClasseDao.salvarObjeto(primeiraClasse);
    }

I want to swap the void of these methods to return success or error, thought to create an object and set the error ...

But I wanted to know how I capture the errors and set in this object.

I don’t know if there’s any other way to work, how you work in this situation?

1 answer

2

The classic way is you drop an Exception and leave the point of the code that invokes your class methods annotated with @Service, solve what to do with it. If you’re working in a web application, an interesting way is to isolate the treatments in a class annotated with @Controlleradvice, which acts as an Interceptor(aspect) focused on your classes annotated with @Controller. Any untreated Exception directly in the controller can be directed to class-specific methods annotated with @Controlleradvice.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.