Imagine I have the following DAO method:
public Employee getEmployeeById(Integer id){
NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(getJdbcTemplate());
String sql = "SELECT * FROM users WHERE id = :userId";
Map<String, Object> parameterMap = new HashMap<String, Object>();
parameterMap.put("userId", id);
return jdbcTemplate.queryForObject(sql, parameterMap, new EmployeeRowMapper());// Throws
//EmptyResultDataAccessException
}
The DAO method is used by the controller method:
public class EmployeeListController{
@Resource(name = "employeeDAO")
private EmployeeDAO employeeDAO;
@RequestMapping(value="/{empId}", method=RequestMethod.GET)
public String getEmployeeById(@PathVariable String empId, Model model){
model.addAttribute("employee", employeeDAO.getEmployeeById(Integer.valueOf(empId)));
return "employeesList";
}
}
Where would be better to handle the Exception? In the controller’s method or the DAO’s method? I think, that in the controller it would be, because otherwise we should return the Object with empty properties, which is not good. Is it correct?
4
The answer to your question “where would it be more appropriate to handle the exception” will depend on what your intended semantics are for the getEmployeeByID
method.
In the .NET Framework, methods that semantically must never throw an exception are prefixed with Try, as in Double.TryParse()
. Usually, you pass a string to parse and a ref
variable, and the function returns a boolean indicating success or failure.
In other words, if you handle the exception in the getEmployeeByID
method, you must also return some status to the caller indicating whether the operation succeeded or not.
Since I don’t see any evidence that your getEmployeeByID
method returns something indicating success or failure, the semantics of your method dictate allowing the exception to pass to the caller. Ergo, you would handle the exception in the EmployeeListController
class.
Further Reading
Does Java have an int.TryParse that doesn’t throw an exception for bad data?
6