Merge pull request #3669 from ebonnecab/error-docs
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Error Docs Revision/Consolidation
authored by David Lord · committed by GitHub · parents f31a8ce, 89d1487 · Browse files · 5 files·+396 added−429 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+396 added−429 removed
- other:+396 added−429 removed
Provenance
- Commit
36e6fc8- Tree
b2f0260- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
f31a8ce- Parent 2
89d1487
5 files changed+396 added−429 removed
modified:docs/blueprints.rst+3 added-2 removed
240 unmodified lines241 242 This will link to ``admin.index`` for instance in case the current request243 was dispatched to any other admin blueprint endpoint.244 245-Error Handlers246---------------245 246+Blueprint Error Handlers247+------------------------248+249 Blueprints support the ``errorhandler`` decorator just like the :class:`Flask`250 application object, so it is easy to make Blueprint-specific custom error251 pages.252 25 unmodified linesadded:docs/debugging.rst+97 added
1+Debugging Application Errors2+============================3+4+5+In Production6+-------------7+8+**Do not run the development server, or enable the built-in debugger, in9+a production environment.** The debugger allows executing arbitrary10+Python code from the browser. It's protected by a pin, but that should11+not be relied on for security.12+13+Use an error logging tool, such as Sentry, as described in14+:ref:`error-logging-tools`, or enable logging and notifications as15+described in :doc:`/logging`.16+17+If you have access to the server, you could add some code to start an18+external debugger if ``request.remote_addr`` matches your IP. Some IDE19+debuggers also have a remote mode so breakpoints on the server can be20+interacted with locally. Only enable a debugger temporarily.21+22+23+The Built-In Debugger24+---------------------25+26+The built-in Werkzeug development server provides a debugger which shows27+an interactive traceback in the browser when an unhandled error occurs28+during a request. This debugger should only be used during development.29+30+.. image:: _static/debugger.png31+ :align: center32+ :class: screenshot33+ :alt: screenshot of debugger in action34+35+.. warning::36+37+ The debugger allows executing arbitrary Python code from the38+ browser. It is protected by a pin, but still represents a major39+ security risk. Do not run the development server or debugger in a40+ production environment.41+42+To enable the debugger, run the development server with the43+``FLASK_ENV`` environment variable set to ``development``. This puts44+Flask in debug mode, which changes how it handles some errors, and45+enables the debugger and reloader.46+47+.. code-block:: text48+49+ $ export FLASK_ENV=development50+ $ flask run51+52+``FLASK_ENV`` can only be set as an environment variable. When running53+from Python code, passing ``debug=True`` enables debug mode, which is54+mostly equivalent. Debug mode can be controled separately from55+``FLASK_ENV`` with the ``FLASK_DEBUG`` environment variable as well.56+57+.. code-block:: python58+59+ app.run(debug=True)60+61+:doc:`/server` and :doc:`/cli` have more information about running the62+debugger, debug mode, and development mode. More information about the63+debugger can be found in the `Werkzeug documentation64+<https://werkzeug.palletsprojects.com/debug/>`__.65+66+67+External Debuggers68+------------------69+70+External debuggers, such as those provided by IDEs, can offer a more71+powerful debugging experience than the built-in debugger. They can also72+be used to step through code during a request before an error is raised,73+or if no error is raised. Some even have a remote mode so you can debug74+code running on another machine.75+76+When using an external debugger, the app should still be in debug mode,77+but it can be useful to disable the built-in debugger and reloader,78+which can interfere.79+80+When running from the command line:81+82+.. code-block:: text83+84+ $ export FLASK_ENV=development85+ $ flask run --no-debugger --no-reload86+87+When running from Python:88+89+.. code-block:: python90+91+ app.run(debug=True, use_debugger=False, use_reloader=False)92+93+Disabling these isn't required, an external debugger will continue to94+work with the following caveats. If the built-in debugger is not95+disabled, it will catch unhandled exceptions before the external96+debugger can. If the reloader is not disabled, it could cause an97+unexpected reload if code changes during debugging.modified:docs/errorhandling.rst+270 added-386 removed
1 Handling Application Errors2 ===========================3 4-.. versionadded:: 0.35-6-Applications fail, servers fail. Sooner or later you will see an exception7-in production. Even if your code is 100% correct, you will still see8-exceptions from time to time. Why? Because everything else involved will9-fail. Here are some situations where perfectly fine code can lead to server4+Applications fail, servers fail. Sooner or later you will see an exception5+in production. Even if your code is 100% correct, you will still see6+exceptions from time to time. Why? Because everything else involved will7+fail. Here are some situations where perfectly fine code can lead to server8 errors:9 10 - the client terminated the request early and the application was still11 reading from the incoming data3 unmodified lines15 - a backend server overloaded16 - a programming error in a library you are using17 - network connection of the server to another system failed18 21-And that's just a small sample of issues you could be facing. So how do we22-deal with that sort of problem? By default if your application runs in19+And that's just a small sample of issues you could be facing. So how do we20+deal with that sort of problem? By default if your application runs in21 production mode, and an exception is raised Flask will display a very simple22 page for you and log the exception to the :attr:`~flask.Flask.logger`.23 24 But there is more you can do, and we will cover some better setups to deal25 with errors including custom exceptions and 3rd party tools.26 27 30-.. _common-error-codes:28+.. _error-logging-tools:29 32-Common Error Codes33-``````````````````30+Error Logging Tools31+-------------------32 35-The following error codes are some that are often displayed to the user,36-even if the application behaves correctly:33+Sending error mails, even if just for critical ones, can become34+overwhelming if enough users are hitting the error and log files are35+typically never looked at. This is why we recommend using `Sentry36+<https://sentry.io/>`_ for dealing with application errors. It's37+available as an Open Source project `on GitHub38+<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version39+<https://sentry.io/signup/>`_ which you can try for free. Sentry40+aggregates duplicate errors, captures the full stack trace and local41+variables for debugging, and sends you mails based on new errors or42+frequency thresholds.43 38-*400 Bad Request*39- When the server will not process the request due to something that40- the server perceives to be a client error. Such as malformed request41- syntax, missing query parameters, etc.44+To use Sentry you need to install the ``sentry-sdk`` client with extra45+``flask`` dependencies.46 43-*403 Forbidden*44- If you have some kind of access control on your website, you will have45- to send a 403 code for disallowed resources. So make sure the user46- is not lost when they try to access a forbidden resource.47+.. code-block:: text48 48-*404 Not Found*49- The good old "chap, you made a mistake typing that URL" message. So50- common that even novices to the internet know that 404 means: damn,51- the thing I was looking for is not there. It's a very good idea to52- make sure there is actually something useful on a 404 page, at least a53- link back to the index.49+ $ pip install sentry-sdk[flask]50 55-*410 Gone*56- Did you know that there the "404 Not Found" has a brother named "41057- Gone"? Few people actually implement that, but the idea is that58- resources that previously existed and got deleted answer with 41059- instead of 404. If you are not deleting documents permanently from60- the database but just mark them as deleted, do the user a favour and61- use the 410 code instead and display a message that what they were62- looking for was deleted for all eternity.51+And then add this to your Flask app:52 64-*500 Internal Server Error*65- Usually happens on programming errors or if the server is overloaded.66- A terribly good idea is to have a nice page there, because your67- application *will* fail sooner or later.53+.. code-block:: python54 55+ import sentry_sdk56+ from sentry_sdk.integrations.flask import FlaskIntegration57 58+ sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])59 71-Default Error Handling72-``````````````````````60+The ``YOUR_DSN_HERE`` value needs to be replaced with the DSN value you61+get from your Sentry installation.62 63+After installation, failures leading to an Internal Server Error64+are automatically reported to Sentry and from there you can65+receive error notifications.66+67+See also:68+69+- Sentry also supports catching errors from a worker queue70+ (RQ, Celery, etc.) in a similar fashion. See the `Python SDK docs71+ <https://docs.sentry.io/platforms/python/>`__ for more information.72+- `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`__73+- `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`__74+75+76+Error Handlers77+--------------78+79+When an error occurs in Flask, an appropriate `HTTP status code80+<https://developer.mozilla.org/en-US/docs/Web/HTTP/Status>`__ will be81+returned. 400-499 indicate errors with the client's request data, or82+about the data requested. 500-599 indicate errors with the server or83+application itself.84+85+You might want to show custom error pages to the user when an error occurs.86+This can be done by registering error handlers.87+88+An error handler is a function that returns a response when a type of error is89+raised, similar to how a view is a function that returns a response when a90+request URL is matched. It is passed the instance of the error being handled,91+which is most likely a :exc:`~werkzeug.exceptions.HTTPException`.92+93+The status code of the response will not be set to the handler's code. Make94+sure to provide the appropriate HTTP status code when returning a response from95+a handler.96+97+98+Registering99+```````````100+101+Register handlers by decorating a function with102+:meth:`~flask.Flask.errorhandler`. Or use103+:meth:`~flask.Flask.register_error_handler` to register the function later.104+Remember to set the error code when returning the response.105+106+.. code-block:: python107+108+ @app.errorhandler(werkzeug.exceptions.BadRequest)109+ def handle_bad_request(e):110+ return 'bad request!', 400111+112+ # or, without the decorator113+ app.register_error_handler(400, handle_bad_request)114+115+:exc:`werkzeug.exceptions.HTTPException` subclasses like116+:exc:`~werkzeug.exceptions.BadRequest` and their HTTP codes are interchangeable117+when registering handlers. (``BadRequest.code == 400``)118+119+Non-standard HTTP codes cannot be registered by code because they are not known120+by Werkzeug. Instead, define a subclass of121+:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and122+register and raise that exception class.123+124+.. code-block:: python125+126+ class InsufficientStorage(werkzeug.exceptions.HTTPException):127+ code = 507128+ description = 'Not enough storage space.'129+130+ app.register_error_handler(InsufficientStorage, handle_507)131+132+ raise InsufficientStorage()133+134+Handlers can be registered for any exception class, not just135+:exc:`~werkzeug.exceptions.HTTPException` subclasses or HTTP status136+codes. Handlers can be registered for a specific class, or for all subclasses137+of a parent class.138+139+140+Handling141+````````142+143 When building a Flask application you *will* run into exceptions. If some part144 of your code breaks while handling a request (and you have no error handlers76-registered) an "500 Internal Server Error"145+registered), a "500 Internal Server Error"146 (:exc:`~werkzeug.exceptions.InternalServerError`) will be returned by default.78-Similarly, if a request is sent to an unregistered route a "404 Not Found"79-(:exc:`~werkzeug.exceptions.NotFound`) error will occur. If a route receives an80-unallowed request method a "405 Method Not Allowed"147+Similarly, "404 Not Found"148+(:exc:`~werkzeug.exceptions.NotFound`) error will occur if a request is sent to an unregistered route.149+If a route receives an unallowed request method, a "405 Method Not Allowed"150 (:exc:`~werkzeug.exceptions.MethodNotAllowed`) will be raised. These are all151 subclasses of :class:`~werkzeug.exceptions.HTTPException` and are provided by152 default in Flask.153 154 Flask gives you to the ability to raise any HTTP exception registered by86-werkzeug. However, as the default HTTP exceptions return simple exception87-pages, Flask also offers the opportunity to customise these HTTP exceptions via88-custom error handlers as well as to add exception handlers for builtin and89-custom exceptions.155+Werkzeug. However, the default HTTP exceptions return simple exception156+pages. You might want to show custom error pages to the user when an error occurs.157+This can be done by registering error handlers.158 91-When an exception is caught by Flask while handling a request, it is first92-looked up by code. If no handler is registered for the code, it is looked up93-by its class hierarchy; the most specific handler is chosen. If no handler is94-registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a159+When Flask catches an exception while handling a request, it is first looked up by code.160+If no handler is registered for the code, Flask looks up the error by its class hierarchy; the most specific handler is chosen.161+If no handler is registered, :class:`~werkzeug.exceptions.HTTPException` subclasses show a162 generic message about their code, while other exceptions are converted to a163 generic "500 Internal Server Error".164 165 For example, if an instance of :exc:`ConnectionRefusedError` is raised,7 unmodified lines173 because the 404 occurs at the routing level before the blueprint can be174 determined.175 176 177+Generic Exception Handlers178+``````````````````````````179 111-.. _handling-errors:180+It is possible to register error handlers for very generic base classes181+such as ``HTTPException`` or even ``Exception``. However, be aware that182+these will catch more than you might expect.183 113-Handling Errors114-```````````````184+For example, an error handler for ``HTTPException`` might be useful for turning185+the default HTML errors pages into JSON. However, this186+handler will trigger for things you don't cause directly, such as 404187+and 405 errors during routing. Be sure to craft your handler carefully188+so you don't lose information about the HTTP error.189 116-Sometimes when building a Flask application, you might want to raise a117-:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that118-something is wrong with the request. Fortunately, Flask comes with a handy119-:func:`~flask.abort` function that aborts a request with a HTTP error from120-werkzeug as desired.121-122-Consider the code below, we might have a user profile route, but if the user123-fails to pass a username we raise a "400 Bad Request" and if the user passes a124-username but we can't find it, we raise a "404 Not Found".125-190 .. code-block:: python191 128- from flask import abort, render_template, request192+ from flask import json193+ from werkzeug.exceptions import HTTPException194 130- # a username needs to be supplied in the query args131- # a successful request would be like /profile?username=jack132- @app.route("/profile")133- def user_profile():134- username = request.arg.get("username")135- # if a username isn't supplied in the request, return a 400 bad request136- if username is None:137- abort(400)195+ @app.errorhandler(HTTPException)196+ def handle_exception(e):197+ """Return JSON instead of HTML for HTTP errors."""198+ # start with the correct headers and status code from the error199+ response = e.get_response()200+ # replace the body with JSON201+ response.data = json.dumps({202+ "code": e.code,203+ "name": e.name,204+ "description": e.description,205+ })206+ response.content_type = "application/json"207+ return response208 139- user = get_user(username=username)140- # if a user can't be found by their username, return 404 not found141- if user is None:142- abort(404)209+An error handler for ``Exception`` might seem useful for changing how210+all errors, even unhandled ones, are presented to the user. However,211+this is similar to doing ``except Exception:`` in Python, it will212+capture *all* otherwise unhandled errors, including all HTTP status213+codes.214 144- return render_template("profile.html", user=user)215+In most cases it will be safer to register handlers for more216+specific exceptions. Since ``HTTPException`` instances are valid WSGI217+responses, you could also pass them through directly.218 146-147-148-.. _custom-error-handlers:149-150-Custom error handlers151-`````````````````````152-153-The default :exc:`~werkzeug.exceptions.HTTPException` returns a black and white154-error page with a basic description, but nothing fancy. Considering155-these errors *will* be thrown during the lifetime of your application, it is156-highly advisable to customise these exceptions to improve the user experience157-of your site. This can be done by registering error handlers.158-159-An error handler is a normal view function that returns a response, but instead160-of being registered for a route, it is registered for an exception or HTTP161-status code that would be raised while trying to handle a request.162-163-It is passed the instance of the error being handled, which is most164-likely an integer that represents a :exc:`~werkzeug.exceptions.HTTPException`165-status code. For example 500 (an "Internal Server Error") which maps to166-:exc:`~werkzeug.exceptions.InternalServerError`.167-168-It is registered with the :meth:`~flask.Flask.errorhandler`169-decorator or the :meth:`~flask.Flask.register_error_handler` to register170-the function later. A handler can be registered for a status code,171-like 404 or 500, or for an built-in exception class, like KeyError,172-or a custom exception class that inherits from Exception or its subclasses.173-174-The status code of the response will not be set to the handler's code. Make175-sure to provide the appropriate HTTP status code when returning a response from176-a handler or a 200 OK HTTP code will be sent instead.177-219 .. code-block:: python220 180- from werkzeug.exceptions import InternalServerError221+ from werkzeug.exceptions import HTTPException222 182- # as a decorator with an int as the exception code183- @app.errorhandler(500)184- def handle_internal_server_error(e):185- # returning 500 with the text sets the error handler's code186- # make sure to provide the appropriate HTTP status code187- # otherwise 200 will be returned as default188- return 'Internal Server Error!', 500223+ @app.errorhandler(Exception)224+ def handle_exception(e):225+ # pass through HTTP errors226+ if isinstance(e, HTTPException):227+ return e228 190- # or, as a decorator with the werkzeug exception for internal server error191- @app.errorhandler(InternalServerError)192- def handle_internal_server_error(e):193- # werkzeug exceptions have a code attribute194- return 'Internal Server Error!', e.code229+ # now you're handling non-HTTP exceptions only230+ return render_template("500_generic.html", e=e), 500231 196- # or, without the decorator197- app.register_error_handler(500, handle_internal_server_error)232+Error handlers still respect the exception class hierarchy. If you233+register handlers for both ``HTTPException`` and ``Exception``, the234+``Exception`` handler will not handle ``HTTPException`` subclasses235+because it the ``HTTPException`` handler is more specific.236 199- # similarly with a werkzeug exception200- app.register_error_handler(InternalServerError, handle_internal_server_error)237 238+Unhandled Exceptions239+````````````````````240 241+When there is no error handler registered for an exception, a 500242+Internal Server Error will be returned instead. See243+:meth:`flask.Flask.handle_exception` for information about this244+behavior.245 204-A handler for "500 Internal Server Error" will not be used when running in205-debug mode. Instead, the interactive debugger will be shown.206-246 If there is an error handler registered for ``InternalServerError``,247 this will be invoked. As of Flask 1.1.0, this error handler will always248 be passed an instance of ``InternalServerError``, not the original249+unhandled error.250+210-unhandled error. The original error is available as ``e.original_exception``.251+The original error is available as ``e.original_exception``.252 Until Werkzeug 1.0.0, this attribute will only exist during unhandled253 errors, use ``getattr`` to get access it for compatibility.254 255 .. code-block:: python8 unmodified lines264 265 # wrapped unhandled error266 return render_template("500_unhandled.html", e=original), 500267 268+An error handler for "500 Internal Server Error" will be passed uncaught exceptions in269+addition to explicit 500 errors. In debug mode, a handler for "500 Internal Server Error" will not be used.270+Instead, the interactive debugger will be shown.271 272 229-Registering Custom Exceptions230------------------------------273+Custom Error Pages274+------------------275 232-You can create your own custom exceptions by subclassing233-:exc:`werkzeug.exceptions.HTTPException`. As shown above, integer HTTP codes234-are interchangable when registering handlers. (``BadRequest.code == 400``)276+Sometimes when building a Flask application, you might want to raise a277+:exc:`~werkzeug.exceptions.HTTPException` to signal to the user that278+something is wrong with the request. Fortunately, Flask comes with a handy279+:func:`~flask.abort` function that aborts a request with a HTTP error from280+werkzeug as desired. It will also provide a plain black and white error page281+for you with a basic description, but nothing fancy.282 236-Non-standard HTTP codes cannot be registered by code because they are not known237-by Werkzeug. Instead, define a subclass of238-:class:`~werkzeug.exceptions.HTTPException` with the appropriate code and239-register and raise that exception class:283+Depending on the error code it is less or more likely for the user to284+actually see such an error.285 286+Consider the code below, we might have a user profile route, and if the user287+fails to pass a username we can raise a "400 Bad Request". If the user passes a288+username and we can't find it, we raise a "404 Not Found".289+290 .. code-block:: python291 243- class InsufficientStorage(werkzeug.exceptions.HTTPException):244- code = 507245- description = 'Not enough storage space.'292+ from flask import abort, render_template, request293 247- def handle_507(e):248- return 'Not enough storage space!', 507294+ # a username needs to be supplied in the query args295+ # a successful request would be like /profile?username=jack296+ @app.route("/profile")297+ def user_profile():298+ username = request.arg.get("username")299+ # if a username isn't supplied in the request, return a 400 bad request300+ if username is None:301+ abort(400)302 250- app.register_error_handler(InsufficientStorage, handle_507)303+ user = get_user(username=username)304+ # if a user can't be found by their username, return 404 not found305+ if user is None:306+ abort(404)307 252- # during an request253- raise InsufficientStorage()308+ return render_template("profile.html", user=user)309 255-Handlers can be registered for any exception class that inherits from Exception.310+Here is another example implementation for a "404 Page Not Found" exception:311 312+.. code-block:: python313 258-Unhandled Exceptions259---------------------314+ from flask import render_template315 261-If an exception is raised in the code while Flask is handling a request and262-there is no error handler registered for that exception, a "500 Internal Server263-Error" will be returned instead. See :meth:`flask.Flask.handle_exception` for264-information about this behavior.316+ @app.errorhandler(404)317+ def page_not_found(e):318+ # note that we set the 404 status explicitly319+ return render_template('404.html'), 404320 266-Custom error pages267-------------------321+When using :doc:`/patterns/appfactories`:322 323+.. code-block:: python324+325+ from flask import Flask, render_template326+327+ def page_not_found(e):328+ return render_template('404.html'), 404329+330+ def create_app(config_filename):331+ app = Flask(__name__)332+ app.register_error_handler(404, page_not_found)333+ return app334+335+An example template might be this:336+337+.. code-block:: html+jinja338+339+ {% extends "layout.html" %}340+ {% block title %}Page Not Found{% endblock %}341+ {% block body %}342+ <h1>Page Not Found</h1>343+ <p>What you were looking for is just not there.344+ <p><a href="{{ url_for('index') }}">go somewhere nice</a>345+ {% endblock %}346+347+348+Further Examples349+````````````````350+351 The above examples wouldn't actually be an improvement on the default352 exception pages. We can create a custom 500.html template like this:353 272-.. sourcecode:: html+jinja354+.. code-block:: html+jinja355 356 {% extends "layout.html" %}357 {% block title %}Internal Server Error{% endblock %}358 {% block body %}12 unmodified lines371 def internal_server_error(e):372 # note that we set the 500 status explicitly373 return render_template('500.html'), 500374 375+When using :doc:`/patterns/appfactories`:376 294-When using the :doc:`/patterns/appfactories`:295-377 .. code-block:: python378 298-379 from flask import Flask, render_template380 381 def internal_server_error(e):382 return render_template('500.html'), 5002 unmodified lines385 app = Flask(__name__)386 app.register_error_handler(500, internal_server_error)387 return app388 309-389 When using :doc:`/blueprints`:390 391 .. code-block:: python392 9 unmodified lines402 # or with register_error_handler403 blog.register_error_handler(500, internal_server_error)404 405 406+Blueprint Error Handlers407+------------------------408 328-In blueprints errorhandlers will simply work as expected; however, there is a caveat329-concerning handlers for 404 and 405 exceptions. These errorhandlers are only330-invoked from an appropriate ``raise`` statement or a call to ``abort`` in another331-of the blueprint's view functions; they are not invoked by, e.g., an invalid URL332-access. This is because the blueprint does not "own" a certain URL space, so333-the application instance has no way of knowing which blueprint error handler it334-should run if given an invalid URL. If you would like to execute different335-handling strategies for these errors based on URL prefixes, they may be defined336-at the application level using the ``request`` proxy object:409+In :doc:`/blueprints`, most error handlers will work as expected.410+However, there is a caveat concerning handlers for 404 and 405411+exceptions. These error handlers are only invoked from an appropriate412+``raise`` statement or a call to ``abort`` in another of the blueprint's413+view functions; they are not invoked by, e.g., an invalid URL access.414 415+This is because the blueprint does not "own" a certain URL space, so416+the application instance has no way of knowing which blueprint error417+handler it should run if given an invalid URL. If you would like to418+execute different handling strategies for these errors based on URL419+prefixes, they may be defined at the application level using the420+``request`` proxy object.421+422 .. code-block:: python423 424 from flask import jsonify, render_template425 8 unmodified lines434 else:435 # otherwise we return our generic site-wide 404 page436 return render_template("404.html"), 404437 354-438 @app.errorhandler(405)439 def method_not_allowed(e):440 # if a request has the wrong method to our API441 if request.path.startswith('/api/'):3 unmodified lines445 # otherwise we return a generic site-wide 405 page446 return render_template("405.html"), 405447 448 449+Returning API Errors as JSON450+----------------------------451 367-More information on error handling with blueprint can be found in368-:doc:`/blueprints`.369-370-371-Returning API errors as JSON372-````````````````````````````373-374-When building APIs in Flask, some developers realise that the builtin452+When building APIs in Flask, some developers realise that the built-in453 exceptions are not expressive enough for APIs and that the content type of454 :mimetype:`text/html` they are emitting is not very useful for API consumers.455 456 Using the same techniques as above and :func:`~flask.json.jsonify` we can return JSON457 responses to API errors. :func:`~flask.abort` is called380-with a ``description`` parameter. The errorhandler will458+with a ``description`` parameter. The error handler will459 use that as the JSON error message, and set the status code to 404.460 461 .. code-block:: python462 11 unmodified lines474 abort(404, description="Resource not found")475 476 return jsonify(resource)477 400-401-402-We can also create custom exception classes; for instance, for an API we can403-introduce a new custom exception that can take a proper human readable message,478+We can also create custom exception classes. For instance, we can479+introduce a new custom exception for an API that can take a proper human readable message,480 a status code for the error and some optional payload to give more context481 for the error.482 483 This is a simple example:34 unmodified lines518 raise InvalidAPIUsage("No such user!", status_code=404)519 520 return jsonify(user.to_dict())521 446-447-A view can now raise that exception with an error message. Additionally522+A view can now raise that exception with an error message. Additionally523 some extra payload can be provided as a dictionary through the `payload`524 parameter.525 526 452-Generic Exception Handlers453-``````````````````````````454-455-It is possible to register error handlers for very generic base classes456-such as ``HTTPException`` or even ``Exception``. However, be aware that457-these will catch more than you might expect.458-459-An error handler for ``HTTPException`` might be useful for turning460-the default HTML errors pages into JSON, for example. However, this461-handler will trigger for things you don't cause directly, such as 404462-and 405 errors during routing. Be sure to craft your handler carefully463-so you don't lose information about the HTTP error.464-465-.. code-block:: python466-467- from flask import json468- from werkzeug.exceptions import HTTPException469-470- @app.errorhandler(HTTPException)471- def handle_exception(e):472- """Return JSON instead of HTML for HTTP errors."""473- # start with the correct headers and status code from the error474- response = e.get_response()475- # replace the body with JSON476- response.data = json.dumps({477- "code": e.code,478- "name": e.name,479- "description": e.description,480- })481- response.content_type = "application/json"482- return response483-484- # or using jsonify485- @app.errorhandler(HTTPException)486- def handle_exception(e):487- return jsonify("code": e.code, "name": e.name, "description": e.description), e.code488-489-490-An error handler for ``Exception`` might seem useful for changing how491-all errors, even unhandled ones, are presented to the user. However,492-this is similar to doing ``except Exception:`` in Python, it will493-capture *all* otherwise unhandled errors, including all HTTP status494-codes. In most cases it will be safer to register handlers for more495-specific exceptions. Since ``HTTPException`` instances are valid WSGI496-responses, you could also pass them through directly.497-498-.. code-block:: python499-500- from werkzeug.exceptions import HTTPException501-502- @app.errorhandler(Exception)503- def handle_exception(e):504- # pass through HTTP errors505- if isinstance(e, HTTPException):506- return e507-508- # now you're handling non-HTTP exceptions only509- return render_template("500_generic.html", e=e), 500510-511-Error handlers still respect the exception class hierarchy. If you512-register handlers for both ``HTTPException`` and ``Exception``, the513-``Exception`` handler will not handle ``HTTPException`` subclasses514-because it the ``HTTPException`` handler is more specific.515-516-517-Generic Error Pages518--------------------519-520-If we pass in the exception into a template as below:521-522-.. code-block:: python523-524- from werkzeug.exceptions import HTTPException525-526- @app.errorhandler(HTTPException)527- def handle_exception(e):528- return render_template("exception.html", e=e), e.code529-530-531-532-.. sourcecode:: html+jinja533-534- {% extends "layout.html" %}535- {% block title %}{{ e.name }}{% endblock %}536- {% block body %}537- <h1>{{ e.code }} {{ e.name }}</h1>538- <p>{{ e.description }}</p>539- <p><a href="{{ url_for('index') }}">Go home</a>540- {% endblock %}541-542-543-544-Debugging Application Errors545-````````````````````````````546-547-For production applications, configure your application with logging and548-notifications as described in :doc:`/logging`. This section provides549-pointers when debugging deployment configuration and digging deeper with a550-full-featured Python debugger.551-527 Logging528 -------529 555-See :doc:`/logging` for information on how to log exceptions, such as by556-emailing them to admins.530+See :doc:`/logging` for information about how to log exceptions, such as531+by emailing them to admins.532 533 534+Debugging535+---------536 560-When in Doubt, Run Manually561----------------------------562-563-Having problems getting your application configured for production? If you564-have shell access to your host, verify that you can run your application565-manually from the shell in the deployment environment. Be sure to run under566-the same user account as the configured deployment to troubleshoot permission567-issues. You can use Flask's builtin development server with `debug=True` on568-your production host, which is helpful in catching configuration issues, but569-**be sure to do this temporarily in a controlled environment.** Do not run in570-production with `debug=True`.571-572-573-.. _working-with-debuggers:574-575-Working with Debuggers576-----------------------577-578-To dig deeper, possibly to trace code execution, Flask provides a debugger out579-of the box (see :ref:`debug-mode`). If you would like to use another Python580-debugger, note that debuggers interfere with each other. You have to set some581-options in order to use your favorite debugger:582-583-* ``debug`` - whether to enable debug mode and catch exceptions584-* ``use_debugger`` - whether to use the internal Flask debugger585-* ``use_reloader`` - whether to reload and fork the process if modules586- were changed587-588-``debug`` must be True (i.e., exceptions must be caught) in order for the other589-two options to have any value.590-591-If you're using Aptana/Eclipse for debugging you'll need to set both592-``use_debugger`` and ``use_reloader`` to False.593-594-A possible useful pattern for configuration is to set the following in your595-config.yaml (change the block as appropriate for your application, of course)::596-597- FLASK:598- DEBUG: True599- DEBUG_WITH_APTANA: True600-601-Then in your application's entry-point (main.py),602-you could have something like::603-604- if __name__ == "__main__":605- # To allow aptana to receive errors, set use_debugger=False606- app = create_app(config="config.yaml")607-608- use_debugger = app.debug and not(app.config.get('DEBUG_WITH_APTANA'))609- app.run(use_debugger=use_debugger, debug=app.debug,610- use_reloader=use_debugger, host='0.0.0.0')611-612-613-.. _error-logging-tools:614-615-616-Error Logging Tools617--------------------618-619-Sending error mails, even if just for critical ones, can become620-overwhelming if enough users are hitting the error and log files are621-typically never looked at. This is why we recommend using `Sentry622-<https://sentry.io/>`_ for dealing with application errors. It's623-available as an Open Source project `on GitHub624-<https://github.com/getsentry/sentry>`_ and is also available as a `hosted version625-<https://sentry.io/signup/>`_ which you can try for free. Sentry626-aggregates duplicate errors, captures the full stack trace and local627-variables for debugging, and sends you mails based on new errors or628-frequency thresholds.629-630-To use Sentry you need to install the `sentry-sdk` client with extra `flask` dependencies::631-632- $ pip install sentry-sdk[flask]633-634-And then add this to your Flask app::635-636- import sentry_sdk637- from sentry_sdk.integrations.flask import FlaskIntegration638-639- sentry_sdk.init('YOUR_DSN_HERE',integrations=[FlaskIntegration()])640-641-The `YOUR_DSN_HERE` value needs to be replaced with the DSN value you get642-from your Sentry installation.643-644-After installation, failures leading to an Internal Server Error645-are automatically reported to Sentry and from there you can646-receive error notifications.647-648-Follow-up reads:649-650-* Sentry also supports catching errors from your worker queue (RQ, Celery) in a651- similar fashion. See the `Python SDK docs652- <https://docs.sentry.io/platforms/python/>`_ for more information.653-* `Getting started with Sentry <https://docs.sentry.io/quickstart/?platform=python>`_654-* `Flask-specific documentation <https://docs.sentry.io/platforms/python/flask/>`_.537+See :doc:`/debugging` for information about how to debug errors in538+development and production.modified:docs/index.rst+1 added
42 unmodified lines43 tutorial/index44 templating45 testing46 errorhandling47+ debugging48 logging49 config50 signals51 views39 unmodified linesmodified:docs/quickstart.rst+25 added-41 removed
109 unmodified lines110 111 The most common reason is a typo or because you did not actually create an112 ``app`` object.113 114-.. _debug-mode:114 115 Debug Mode116 ----------117 119-(Want to just log errors and stack traces? See :doc:`errorhandling`)118+The ``flask run`` command can do more than just start the development119+server. By enabling debug mode, the server will automatically reload if120+code changes, and will show an interactive debugger in the browser if an121+error occurs during a request.122 121-The :command:`flask` script is nice to start a local development server, but122-you would have to restart it manually after each change to your code.123-That is not very nice and Flask can do better. If you enable debug124-support the server will reload itself on code changes, and it will also125-provide you with a helpful debugger if things go wrong.123+.. image:: _static/debugger.png124+ :align: center125+ :class: screenshot126+ :alt: The interactive debugger in action.127 127-To enable all development features (including debug mode) you can export128-the ``FLASK_ENV`` environment variable and set it to ``development``129-before running the server::128+.. warning::129 131- $ export FLASK_ENV=development132- $ flask run130+ The debugger allows executing arbitrary Python code from the131+ browser. It is protected by a pin, but still represents a major132+ security risk. Do not run the development server or debugger in a133+ production environment.134 134-(On Windows you need to use ``set`` instead of ``export``.)135+To enable all development features, set the ``FLASK_ENV`` environment136+variable to ``development`` before calling ``flask run``.137 136-This does the following things:138+.. code-block:: text139 138-1. it activates the debugger139-2. it activates the automatic reloader140-3. it enables the debug mode on the Flask application.140+ $ export FLASK_ENV=development141+ $ flask run142 142-You can also control debug mode separately from the environment by143-exporting ``FLASK_DEBUG=1``.143+See also:144 145-There are more parameters that are explained in :doc:`/server`.145+- :doc:`/server` and :doc:`/cli` for information about running in146+ development mode.147+- :doc:`/debugging` for information about using the built-in debugger148+ and other debuggers.149+- :doc:`/logging` and :doc:`/errorhandling` to log errors and display150+ nice error pages.151 147-.. admonition:: Attention152 149- Even though the interactive debugger does not work in forking environments150- (which makes it nearly impossible to use on production servers), it still151- allows the execution of arbitrary code. This makes it a major security risk152- and therefore it **must never be used on production machines**.153-154-Screenshot of the debugger in action:155-156-.. image:: _static/debugger.png157- :align: center158- :class: screenshot159- :alt: screenshot of debugger in action160-161-More information on using the debugger can be found in the `Werkzeug162-documentation`_.163-164-.. _Werkzeug documentation: https://werkzeug.palletsprojects.com/debug/#using-the-debugger165-166-Have another debugger in mind? See :ref:`working-with-debuggers`.167-168-153 HTML Escaping154 -------------155 156 When returning HTML (the default response type in Flask), any747 unmodified lines