简体   繁体   English

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

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

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. 但是error.message变量是一个空字符串。 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 我似乎无法找到有关如何使用自定义错误处理程序访问中止函数的第二个变量的文档

If you look at flask/__init__.py you will see that abort is actually imported from werkzeug.exceptions . 如果你看看flask/__init__.py你会看到abort实际上是从werkzeug.exceptions导入的。 Looking at the Aborter class , we can see that when called with a numeric code, the particular HTTPException subclass is looked up and called with all of the arguments provided to the Aborter instance. 查看Aborter ,我们可以看到,当使用数字代码调用时,将查找特定的HTTPException子类,并使用提供给Aborter实例的所有参数进行Aborter Looking at HTTPException , paying particular attention to lines 85-89 we can see that the second argument passed to HTTPException.__init__ is stored in the description property, as @dirn pointed out. 查看HTTPException ,特别注意第85-89行,我们可以看到传递给HTTPException.__init__的第二个参数存储在description属性中,正如@dirn指出的那样。

You can either access the message from the description property: 您可以从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')

People rely on abort() too much. 人们过分依赖abort() The truth is that there are much better ways to handle errors. 事实是,有更好的方法来处理错误。

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. 我希望这有帮助。

我只是这样做:

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

flask.abort也接受flask.Response

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python Flask - Abort - 自定义错误消息不再起作用 - Python Flask - Abort - Custom error message does not working anymore 如何从ValidationError访问错误消息? - How to access error message from ValidationError? 使用 message_handler (telebot) 时出错 - Error while using message_handler (telebot) 为什么我收到我的自定义日志处理程序“没有属性`level`”的错误消息? - Why I get the error message that my custom logging handler "has no attribute `level`"? 使用 python 脚本中的 cat 命令时收到错误消息“raise CalledProcessError(retcode, cmd)” - Getting the error message "raise CalledProcessError(retcode, cmd)" when using the cat command from a python script 在python中使用自定义异常时出错 - Get error when using custom exception in python 启动 Intel python3.7 shell 时出现意外错误:无法执行任何命令 - 中止错误 - Unexpected error when Intel python3.7 shell is launched : impossible to do any command - abort error 如何在 discord.py 中创建自定义异常/错误处理程序 class 来处理命令特定错误? - How to create an custom Exception/Error Handler class in discord.py which would handle command specific errors? 如何打印自定义错误消息? - How to print custom error message? 如何在Aiogram的调度器中从message_handler中排除/command? - How to exclude the /command from message_handler in the dispatcher of Aiogram?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM