clj-commons / secretary

A client-side router for ClojureScript.
773 stars 64 forks source link

Invalid URL handling #87

Open kamituel opened 7 years ago

kamituel commented 7 years ago

When invalid URL is entered by the user, such as:

http://host/some/path?param=val%%ue

encodeURIComponent and/or decodeURIComponent throw an unhandled exception and Secretary stops working. It would be nice if Secretary would be able to let app know such thing happened (it might be a bug in the app itself, invalid route, or something else) so that an app could do whatever it thinks makes sense.

So something like that maybe (this is just a out of the top of my head proposal):

(defroute :invalid-url [] ...)

Is such a thing possible with Secretary out of the box?

In our project we needed to handle it recently and so far I worked around it with this JS snippet that redirects to the "/error-path" with a proper error message. This is far from being ideal though.

(function() {
  var wrapWithCatch = function(fnName) {
    var orig = window[fnName];
    window[fnName] = function() {
      try {
        return orig.apply(null, arguments);
      } catch (e) {
        console.error("Error in " + fnName + ", redirecting.", e);
        window.location.hash = "/error-path";
      }
    };
  };

  wrapWithCatch("decodeURIComponent");
  wrapWithCatch("encodeURIComponent");
})();