Glue together Turbolinks UJS/SJR + Stimulus + BetterErrors

Wanted to share a small snippet I added to a project today. Have been moving more and more to Turbolinks + SJR and ran into an annoyance when my remote: true links/forms got an error. I had to click through the network tab to see the error message.

Assuming you have better-errors installed already:

Throw this snippet somewhere in your application template:

<% if Rails.env.development? %>
  <div class="hidden" 
          data-controller="better-errors" 
          data-action="ajax:error@document->better-errors#show" /></div>
<% end %>

And add this controller

// better_errors_controller.js

import { Controller } from "stimulus";

export default class extends Controller {
  show() {
    Turbolinks.visit("/__better_errors");
  }
}

This wires up the Rails ajax:error event to send to you the special “manual console” route where BetterErrors shows the last exception with stack trace and other goodies.

Hope it saves you some headaches!

7 Likes