Rails jumps to the uniform error page when an error occurs.
A website in iterative development is prone to bugs, and the customer experience is poor when a bug occurs. To solve this problem, you can trigger the jump to the unified prompt page when a class error occurs, and sends an email to the developer to improve the test capability and user experience. The following is the core method. The following code is added to ApplicationController. The class error varies slightly in different rails versions.
Copy codeThe Code is as follows:
AR_ERROR_CLASSES = [ActiveRecord: RecordNotFound, ActiveRecord: StatementInvalid]
ERROR_CLASSES = [NameError, NoMethodError, RuntimeError,
ActionView: TemplateError,
ActiveRecord: StaleObjectError, ActionController: RoutingError,
ActionController: UnknownController, AbstractController: ActionNotFound,
ActionController: MethodNotAllowed, ActionController: InvalidAuthenticityToken]
ACCESS_DENIED_CLASSES = [CanCan: AccessDenied]
If Rails. env. production?
Rescue_from * AR_ERROR_CLASSES,: with =>: render_ar_error
Rescue_from * ERROR_CLASSES,: with =>: render_error
Rescue_from * ACCESS_DENIED_CLASSES,: with =>: render_access_denied
End
# Called by last route matching unmatched routes. Raises RoutingError which will be rescued from in the same way as other exceptions.
# Note: After rails3.1, The ActionController: RoutingError can be caught only when the following code is added at the end of routes. rb.
# Match '* unmatched_route' under rails3,: to => 'application # raise_not_found! '
# In rails4: get '* unmatched_route',: to => 'application # raise_not_found! '
Def raise_not_found!
Raise ActionController: RoutingError. new ("No route matches # {params [: unmatched_route]}")
End
Def render_ar_error (exception)
Case exception
When * AR_ERROR_CLASSES then exception_class = exception. class. to_s
Else exception_class = 'exception'
End
Send_error_email (exception, exception_class)
End
Def render_error (exception)
Case exception
When * ERROR_CLASSES then exception_class = exception. class. to_s
Else exception_class = 'exception'
End
Send_error_email (exception, exception_class)
End
Def render_access_denied (exception)
Case exception
When * ACCESS_DENIED_CLASSES then exception_class = exception. class. to_s
Else exception_class = "Exception"
End
Send_error_email (exception, exception_class)
End