2017-08-04 78 views
0

在我的應用程序的服務級別,我提出了一個異常,我希望它被打印爲瀏覽器的JSON。Falcon - 將異常提升爲json

我實現它的文檔中所述:

raise falcon.HTTPError(
    '12345 - My Custom Error', 
    'some text' 
).to_json() 

而且從控制檯輸出:

TypeError: exceptions must derive from BaseException 

任何人都收到這個問題,可以幫助我這個嗎?

感謝和問候!

回答

1

你試圖提高一個字符串。正確的方法是使用set_error_serializer()

文檔中的例子看起來正是您需要的(加上YAML支持)。

def my_serializer(req, resp, exception): 
    representation = None 

    preferred = req.client_prefers(('application/x-yaml', 
            'application/json')) 

    if preferred is not None: 
     if preferred == 'application/json': 
      representation = exception.to_json() 
     else: 
      representation = yaml.dump(exception.to_dict(), 
             encoding=None) 
     resp.body = representation 
     resp.content_type = preferred 

    resp.append_header('Vary', 'Accept') 

app = falcon.API() 
app.set_error_serializer(my_serializer) 
+0

哎謝謝你的回答,太棒了:)還有一個問題,爲什麼我需要yaml時,每個瀏覽器都支持json和json它的首選格式? 不能我只是做「resp.body = exception.to_json()」? –

+0

你不需要瀏覽器。通常你會用python,php等方式給高級用戶。 – kichik