Skip to content

Conversation

@ganyicz
Copy link
Collaborator

@ganyicz ganyicz commented Sep 3, 2025

This PR adds the ability to customize error handling by exposing a setErrorHandler function on the Alpine object.

Why?

To enable development of packages that enrich errors with debugging info like source file location.

This can be particularly useful when working with a server-rendered templating engine like Blade, where locating expressions based on console output can be difficult. This is especially true when using Blade components.

The main reason is that the source code is split across multiple files and often looks very different from the code rendered in the browser. Since Alpine only ever interacts with the rendered HTML, it can’t provide any information about where the code originated.

This is where a package that integrates Blade with Alpine can help. It can gather information about the location of expressions and, when an error is thrown, display it in the browser. For example:

IMG_8112

How?

By adding debug information to the rendered HTML, which can then be formatted by the custom error handler.

I’m currently working on a package that does exactly this. You can look at the implementation of this method here:

https://github.com/ganyicz/bond/blob/ccfcc57b1e1e15794c8bcf403df239277af015a3/packages/alpine-plugin/src/index.js#L170-L208

The package inspects Blade files during compilation and adds a comment at the end of each expression. This comment can be either an identifier or the debug info itself. The custom error handler then picks it up, removes it from the expression, and adds the debug info to the final error message, producing the result shown above.

Here’s an example of an attribute containing this debug comment:

x-on:click="handleClick/*debug:file:line*/"

Implementation

I made sure to keep the changes minimal, follow existing conventions, avoid breaking changes, and include a small test.

The PR refactors the current handleError method to call a function stored in a local errorHandler variable, which can be overridden externally using the setErrorHandler function. By default, it is set to normalErrorHandler, which contains the same code that previously existed in handleError. This pattern is already used in the evaluator, and the implementation follows the same naming conventions and style.

@calebporzio calebporzio merged commit 4ea3d71 into alpinejs:main Nov 1, 2025
1 check passed
@calebporzio
Copy link
Collaborator

😉 thanks Filip!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants