Python 使用自定义错误处理程序时如何从 abort 命令访问错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21294889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:31:20  来源:igfitidea点击:

how to get access to error message from abort command when using custom error handler

pythonhttpflaskhttp-error

提问by richmb

Using a python flask server, I want to be able to throw an http error response with the abort command and use a custom response string and a custom message in the body

使用 python Flask 服务器,我希望能够使用 abort 命令抛出 http 错误响应并在正文中使用自定义响应字符串和自定义消息

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.message})
    response.status_code = 404
    response.status = 'error.Bad Request'
    return response

abort(400,'{"message":"custom error message to appear in body"}')

But the error.message variable comes up as an empty string. I can't seem to find documentation on how to get access to the second variable of the abort function with a custom error handler

但是 error.message 变量作为一个空字符串出现。我似乎找不到有关如何使用自定义错误处理程序访问 abort 函数的第二个变量的文档

采纳答案by Sean Vieira

If you look at flask/__init__.pyyou will see that abortis actually imported from werkzeug.exceptions. Looking at the Aborterclass, we can see that when called with a numeric code, the particular HTTPExceptionsubclass is looked up and called with all of the arguments provided to the Aborterinstance. Looking at HTTPException, paying particular attention to lines 85-89we can see that the second argument passed to HTTPException.__init__is stored in the descriptionproperty, as @dirn pointed out.

如果你看一下,flask/__init__.py你会看到它abort实际上是从werkzeug.exceptions. 查看Aborterclass,我们可以看到,当使用数字代码调用时,HTTPException会查找特定子类并使用提供给Aborter实例的所有参数进行调用。查看HTTPException,特别注意第 85-89 行,我们可以看到传递给的第二个参数HTTPException.__init__存储在description属性中,正如@dirn 指出的那样。

You can either access the message from the descriptionproperty:

您可以从description属性访问消息:

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.description['message']})
    # etc.

abort(400, {'message': 'custom error message to appear in body'})

or just pass the description in by itself:

或者自己传递描述:

@app.errorhandler(400)
def custom400(error):
    response = jsonify({'message': error.description})
    # etc.

abort(400, 'custom error message to appear in body')

回答by Miguel

People rely on abort()too much. The truth is that there are much better ways to handle errors.

人们abort()过于依赖。事实是,有更好的方法来处理错误。

For example, you can write this helper function:

例如,您可以编写此辅助函数:

def bad_request(message):
    response = jsonify({'message': message})
    response.status_code = 400
    return response

Then from your view function you can return an error with:

然后从您的视图函数中,您可以返回一个错误:

@app.route('/')
def index():
    if error_condition:
        return bad_request('message that appears in body')

If the error occurs deeper in your call stack in a place where returning a response isn't possible then you can use a custom exception. For example:

如果错误发生在调用堆栈的更深处,并且无法返回响应,那么您可以使用自定义异常。例如:

class BadRequestError(ValueError):
    pass

@app.errorhandler(BadRequestError)
def bad_request_handler(error):
    return bad_request(str(error))

Then in the function that needs to issue the error you just raise the exception:

然后在需要发出错误的函数中,您只需引发异常:

def some_function():
    if error_condition:
        raise BadRequestError('message that appears in the body')

I hope this helps.

我希望这有帮助。

回答by Vasili Pascal

I simply do it like this:

我只是这样做:

    abort(400, description="Required parameter is missing")

回答by Neil

flask.abortalso accepts flask.Response

flask.abort也接受 flask.Response

abort(make_response(jsonify(message="Error message"), 400))