Where should I put the Try / Catch blocks using MVC?

2

I am doing a web application in java and I have some doubts regarding the try catch block, I am using the MVC standard and I have the following codes:

Controller:

try {
    String pesquisa = "%" + request.getParameter("pesquisa") + "%";
    List<Administrador> adm = serviceAdm.listarAdm(pesquisa);

    request.setAttribute("adm", adm);
    RequestDispatcher disp = request.getRequestDispatcher("administradores.jsp");
    disp.forward(request, response);
} catch (Exception ex) {
    System.out.println("Erro: " + ex);
    request.setAttribute("erro", true);
    RequestDispatcher disp = request.getRequestDispatcher("principal.jsp");
    disp.forward(request, response);
}

Model:

public List<Administrador> listarAdm(String pesquisa) {
    try {
        return (List<Administrador>) admDB.selectAdms(pesquisa);
    } catch (Exception ex) {
        return null;
    }
}

And I use DAO to make the connection:

public List<Administrador> selectAdms(String pesquisa) {
    List<Administrador> usuarios = manager
            .createQuery("select a from Administrador a where nome LIKE :pesquisa")
            .setParameter("pesquisa", pesquisa).getResultList();

    return usuarios;
}

I would like to know if I have a problem with Model, as I put it to return null , it will not enter the Controller catch? Should I put try/catch in all files or only Controllers ?

    
asked by anonymous 14.11.2016 / 15:51

2 answers

0

The idea of using try catch is just to catch exceptions that the application can launch and perform an alternative operation. So you should put try catch scopes every time the application can throw an error, ie if an error can occur in a file, try try catch.

By its code, the catch of the controller throws an exception because you try to use a variable that is null. So your logic will work correctly.

    
14.11.2016 / 16:07
1

You can use throws in the signature of the methods of the model to echo the exceptions directly to the Controller instead of try catch or use try catch itself and within the catch you make a throw new to specify the error generated in the model. / p>     

14.11.2016 / 17:54