@@ -212,6 +212,40 @@ def url_for(endpoint, **values):
212
212
213
213
For more information, head over to the :ref:`Quickstart <url-building>`.
214
214
215
+ To integrate applications, :class:`Flask` has a hook to intercept URL build
216
+ errors through :attr:`Flask.build_error_handler`. The `url_for` function
217
+ results in a :exc:`~werkzeug.routing.BuildError` when the current app does
218
+ not have a URL for the given endpoint and values. When it does, the
219
+ :data:`~flask.current_app` calls its :attr:`~Flask.build_error_handler` if
220
+ it is not `None`, which can return a string to use as the result of
221
+ `url_for` (instead of `url_for`'s default to raise the
222
+ :exc:`~werkzeug.routing.BuildError` exception) or re-raise the exception.
223
+ An example::
224
+
225
+ def external_url_handler(error, endpoint, **values):
226
+ "Looks up an external URL when `url_for` cannot build a URL."
227
+ # This is an example of hooking the build_error_handler.
228
+ # Here, lookup_url is some utility function you've built
229
+ # which looks up the endpoint in some external URL registry.
230
+ url = lookup_url(http://github.com/endpoint,%20**values)
231
+ if url is None:
232
+ # External lookup did not have a URL.
233
+ # Re-raise the BuildError, in context of original traceback.
234
+ exc_type, exc_value, tb = sys.exc_info()
235
+ if exc_value is error:
236
+ raise exc_type, exc_value, tb
237
+ else:
238
+ raise error
239
+ # url_for will use this result, instead of raising BuildError.
240
+ return url
241
+
242
+ app.build_error_handler = external_url_handler
243
+
244
+ Here, `error` is the instance of :exc:`~werkzeug.routing.BuildError`, and
245
+ `endpoint` and `**values` are the arguments passed into `url_for`. Note
246
+ that this is for building URLs outside the current application, and not for
247
+ handling 404 NotFound errors.
248
+
215
249
.. versionadded:: 0.9
216
250
The `_anchor` and `_method` parameters were added.
217
251
0 commit comments