flask-jwt-extended: Integration with flask-restful & error handling

Similar to #86, errors like SignatureExpiry are returning 500 rather than 4xx errors.

However I am using flask-restful which does not have an error_handler, so the solutions in the referenced issue do not apply.

Flask-restful is briefly mentioned on the releases page here , but setting application.config['PROPAGATE_EXCEPTIONS'] = True didn’t have any effect for me.

Any insight into how I can correctly deal with error handling using flask-restful?

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 15 (5 by maintainers)

Commits related to this issue

Most upvoted comments

I also encountered this issue. I could not replicate it at all in development, but was getting 500s instead of 401s in production and staging.

I was able to reproduce it by setting the debug setting to false in development mode, and the 500s showed up.

I was able to fix it by setting application.config['PROPAGATE_EXCEPTIONS'] = True

Another solution for anyone who is hitting the 500 internal server error instead of the expected 401, 4XX error as expected when using flask_restful:

from flask import Flask
from flask_restful import Resource, Api
from flask_jwt import JWT, jwt_required

app = Flask(__name__)
app.secret_key = "yourSecretKeyHere"
api = Api(app, errors=Flask.errorhandler)

This enabled me to change from this before implementation:

{
    "message": "Internal Server Error"
}

To this post implementation:

{
    "description": "Request does not contain an access token",
    "error": "Authorization Required",
    "status_code": 401
}

@paurakhsharma

I think I found a workaround to integrate custom errors. Here’s my current setup: Set PROPAGATE_EXCEPTIONS = False Then overwrite the error handler flask_restful.Api object as such:

from flask import Blueprint
from flask_restful import Api as _Api

# some custom errors
class RoomDoesNotExist(Exception):
    pass

CUSTOM_ERRORS = {
'RoomDoesNotExist': {
        'message': "A room by that name does not exist.",
        'status': 404,
    },
}

class Api(_Api):
    def error_router(self, original_handler, e):
        """ Override original error_router to only custom errors and parsing error (from webargs)"""
        error_type = type(e).__name__.split(".")[-1] # extract the error class name as a string
        # if error can be handled by flask_restful's Api object, do so
        # otherwise, let Flask handle the error
        # the 'UnprocessableEntity' is included only because I'm also using webargs
        # feel free to omit it
        if self._has_fr_route() and error_type in list(CUSTOM_ERRORS) + ['UnprocessableEntity']:
            try:
                return self.handle_error(e)
            except Exception:
                pass  # Fall through to original handler

        return original_handler(e)

api_bp = Blueprint('api', __name__)
api = Api(api_bp, errors=CUSTOM_ERRORS)

This way, flask_restful’s errors are handled by flask_restful’s Api object, and other errors fall through to Flask’s error handler.

I am encountering the issue, and

I also encountered this issue. I could not replicate it at all in development, but was getting 500s instead of 401s in production and staging.

I was able to reproduce it by setting the debug setting to false in development mode, and the 500s showed up.

I was able to fix it by setting application.config['PROPAGATE_EXCEPTIONS'] = True

doesn’t exactly do the trick for my setup.

I’m using Flask-Restful’s custom errors. It is true that setting application.config['PROPAGATE_EXCEPTIONS'] = True fixes the errors propagating from JWT, but this setting also causes any custom error message to show up as 500s, instead of 400s. So if PROPAGATE_EXCEPTIONS, JWT errors don’t work. If not PROPAGATE_EXCEPTIONS, custom errors break. It’s a bit of an unexpected dilemma.

Is there any way to work around this without requiring PROPAGATE_EXCEPTIONS to be set?

@alexding123 many many thanks for your solution! That’s the only way I’ve found so far to bypass this annoying issue