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

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

问题描述

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

< pre $ @ 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变量是空字符串。我似乎无法找到关于如何访问中止函数的第二个变量与自定义错误处理程序的文档

解决方案

如果你看 flask / __ init __。py ,你会发现 abort 实际上是从 werkzeug.exceptions 。查看 中止者,我们可以看到,当用一个数字代码调用时,查找特定的 HTTPException 子类并调用所有提供给 Aborter 实例。查看 HTTPException ,特别注意 85-89行,我们可以看到如@dirn指出的那样,传递给 HTTPException .__ init __ 的第二个参数存储在 description 属性中。您可以从描述属性中访问消息:



$ b < pre $ @ app.errorhandler(400)
def custom400(error):
response = jsonify({'message':error.description ['message']} )
#等

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

或者只是传递描述本身:

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

abort(400,'body error'to body in body')


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

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

解决方案

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.

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

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')

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

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