Read more

Unpoly: Automatically show the full better_errors page when Rails raises an error

Henning Koch
July 24, 2019Software engineer at makandra GmbH

When an AJAX request raises an exception on the server, Rails will show a minimal error page with only basic information. Because all Unpoly Show archive.org snapshot updates work using AJAX requests, you won't get the more detailled better_errors Show archive.org snapshot page with the interactive REPL Show archive.org snapshot .

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

Below is an event listener that automatically repeats the request as a full-page load if your development error shows an error page. This means you get a second request, but the error page will show with full CSS and JavaScript.

The code assumes you are using Ruby on Rails with better_errors Show archive.org snapshot , which is the default error view that modern Rails versions employ. If you are using another method to show development errors you need to update the isDevelopmentError() function so it returns true when your particular development server shows an error.

Unpoly >= 2.x

// Only do this in development. This requires a `[data-environment="development"]` attribute on your `<body>` element. 
// See https://makandracards.com/makandra/1433-detect-the-current-rails-environment-from-javascript-or-css
if (document.body.dataset.environment == 'development') {

  // Returns true when your development server shows an error page.
  function isDevelopmentError(response) {
    return !response.ok && /Full backtrace|Better errors/.test(response.text)
  }

  // When the development server shows an error page, repeat the request as a full page load.
  up.on('up:fragment:loaded', function(event) {
    if (isDevelopmentError(event.response)) {
      event.preventDefault() // Prevent the fragment from being updated
      event.request.loadPage()
    }
  })

}

Unpoly 0.x, 1.x

// Only do this in development. This requires a `[data-environment="development"]` attribute on your `<body>` element. 
// See https://makandracards.com/makandra/1433-detect-the-current-rails-environment-from-javascript-or-css
if (document.body.dataset.environment == 'development') {

  // Returns true when your development server shows an error page.
  function isDevelopmentError(response) {
    return response.isError() && /Full backtrace|Better errors/.test(response.text)
  }

  // When the development server shows an error page, repeat the request as a full page load.
  up.on('up:proxy:loaded', function(event) {
    if (isDevelopmentError(event.response)) {
      event.request.navigate()
    }
  })

}
Posted by Henning Koch to makandra dev (2019-07-24 08:39)