Methods that return a hash or an exception?

Hi everyone,

I’m not quite sure how to handle this type of thing. I have a method
that searches for a user in our LDAP by way of a Person model’s
username attribute:

@ldap_person = @person.get_ldap_user

This method, noce done with the LDAP wrangling, returns the user entry
(an LDAP::Entry object) as a hash:

return conn.search2(UnifiedLDAP::PEOPLE_DN, LDAP::LDAP_SCOPE_SUBTREE,
filter, self.ldap_attributes)[0].to_hash

This works, and, of course, there SHOULD be an LDAP entry
corresponding to that Person, but if there isn’t or LDAP is
unreachable, I want to report that. Am I doing the wrong thing in
returning a hash? Where should I be catching exceptions? How should
I be then be dealing with them?

This is part of a Rails app, but I don’t think that part is important,
so I’m sticking to this list. When I pass @ldap_person to the view,
though, and @ldap_person is an exception, obviously, this doesn’t
work.

Thank you!

Sean

Sean H. wrote:

so I’m sticking to this list. When I pass @ldap_person to the view,
though, and @ldap_person is an exception, obviously, this doesn’t
work.

One idea off the top of my head would be to catch the exception in
#get_ldap_user and have the rescue clause return nil. Then, when you
pass @ldap_person to your view, you could have something like: <%
@ldap_person || “” %> in your rhtml file, so that if @ldap_person is
nil, it just prints an empty string.

HTH,

Jamey

Ok, yeah, that worked. Thanks! There’s a little more code in the
view and controller than I’d like, but I’ll be able to refactor that
as I get better at Ruby. :slight_smile:

What I have now (the Person model just returns nil if there was an
exception):

if !(@ldap_person = @person.get_ldap_user)
flash[:error] = “User does not exist in LDAP or LDAP unreachable”
end

View:

<% if flash[:error] %>
<%= flash[:error] %>
<% flash[:error] = nil %>
<% else %>
…everything else for a successful user find…
<% end %>

So, yeah, not the best, but it definitely gets me to a place where I
can show this to the client and work on fleshing out error handling a
bit more.

Thank you!

Sean