ruby on rails - How to check if variable has error -
how check if variable has error in controller before going view.
in controller:
def index @sample_model = model.all rescue => e flash.now[:alert] = e.message end
for example have error activerecord::statementinvalid: mysql2::error: table 'models' doesn't exist: ...
i want check if first before going view can show flash.
i looking forward seeing solution (this not answer in itself); wanted highlight several points:
i want check if first before going view so can show flash.
how expect show error in flash?
much of time, errors of nature cause equivalent of fatal exception
, preventing application making progress.
when type of thing happens, rails has middleware catches exception, passing error handling pages. i'll explain in minute.
the fact remains, though, if you're going receive error - how expect rest of stack work? maybe mysql table doesn't exist -- if you're calling same data in layout or something?
what you're looking 1 of 2 things:
- a way handle specific errors (ie no data)
- a way rescue exceptions in controlled manner (ie without having default "exception" page rails.
this not answer, help...
all rails exceptions handled middleware hook called config.exceptions_app
:
the actual middleware actiondispatch::showexception
, can seen here.
any of "custom exception page" tutorials hook config.exceptions_app
middleware, either self.routes
or controller call.
i've been involved custom error pages time; i wrote gem it. there several important points understand it.
rails invokes 2 sets of errors - 40x
& 50x
:
40x
(like404
) missing resources50x
(like500
) server faults.
the difference between 2 404 errors (either no routes, or no data), not fatal. 500 errors are fatal (as prevent app functioning).
500 errors cannot rescued rest of app's infrastructure; database having no connection variable not having values.
what type of errors expecting rescue?
as such, if it's "no data" error, you'll able handle @variable.nil?
conditions.
if it's more serious (a problem further stack), expect happen? view & layout load no data? if db connectivity broken?
--
the best recommendation can give handle app-level exceptions within controller & view, eg:
#app/views/data/object.html.erb <% if @variable.any? %>
if want "prettify" error pages, you'll best using 1 of recommendations here, or using exception_handler
gem helped write.
Comments
Post a Comment