使用自定义错误处理程序时如何从 abort 命令访问错误消息 [英] how to get access to error message from abort command when using custom error handler

查看:32
本文介绍了使用自定义错误处理程序时如何从 abort 命令访问错误消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

@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"}')

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

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

推荐答案

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

If you look at flask/__init__.py you will see that abort is actually imported from 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. 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.

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

You can either access the message from the description property:

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

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

或者自己传递描述:

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

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

这篇关于使用自定义错误处理程序时如何从 abort 命令访问错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆