connexion: Custom validation error handler

Description

I need some help about how to catch and provide a custom handler for validation errors. This is not an error in the validation itself, but a legit problem with an expected parameter that’s misspelled. This generates the connexion response:

{
  "detail": "<details about the problem>"
  "status": 400, 
  "title": "Bad Request", 
  "type": "about:blank"
}

This is fine, but I’d like to catch this and reformat the above data into a message structure my application is expecting. I’ve tried using add_error_handler(400, <handler>) and the Flask @app.errorhandler(400), but neither catches the error. I’m sure I’m missing something in the documentation, but could use a pointer/suggestion about how to do what I’m trying to do.

Thanks in advance, Doug

Version Information

Python - Python 2.7.5 Connexion - Version: 1.1.10.1

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 2
  • Comments: 16 (4 by maintainers)

Most upvoted comments

Hi Leena,

Thanks for your response and the clarification about the RequestBodyValidator. I modified my code to reflect what you wrote, but still no luck, I can’t get the system to call my ‘bad_request_error_handler()’ for a validation error. Here’s a simplified version of my code:

import connexion
from connexion import decorators
from jsonschema import ValidationError

class RequestBodyValidator(decorators.validation.RequestBodyValidator):
    def validate_schema(self, data):
        if self.is_null_value_valid and connexion.utils.is_null(data):
            return None
        self.validator.validate(data)

def bad_request_error_handler(error):
    v = 1

def create_app(config_key, instance_config=None):
    # create the connexion instance
    connex_app = connexion.FlaskApp(__name__,
                                    specification_dir='./files/swagger/',
                                    validator_map={
                                        'body': RequestBodyValidator
                                    })
    connex_app.add_error_handler(ValidationError, bad_request_error_handler)

Again, thanks for your help with this.

Doug

@LeenaBhegade Clarification in documentation or a patch is needed.

add_api() has no keyword arg validator_map so I suspect it falls into “old style options”. If the documented approach (in user manual) is deprecated as “old style”, then please tell us what is the current and proper way to do this.

thanks marc