簡體   English   中英

避免在端點上引發異常的最佳實踐?

[英]Best practice to avoid throwing exceptions on endpoints?

我正在使用Bottle公開HTTP端點(僅輸出JSON)。

當前拋出{'error': %s, 'error_message': %s, 'status_code': #}{'error': %s, 'error_message': %s, 'status_code': #}

因此,在所有終結點裝飾函數中,我都有:

try:
    someObj = <stuff>
except <MyCustomErrors> as e:
    response.status = e.response.pop('status_code', 500)
    return e.response

response.status = someObj.response.pop('status_code', 200)

return someObj.response

但是我可以很輕松地避免一起使用異常,從而在減少開銷的情況下使用更簡潔的DRYer端點代碼。

但是有缺點。 其他開發人員將需要至少閱讀或運行一次代碼以了解輸出格式。

文檔將在這里工作; 但是,這整個設置是不好的做法嗎?

同時,我寫了這個可憐的替代品:

# Not a decorator because I can't work out how to give `@route(apply=)` func args
def error_else_response(init_with):
    try:
        result = init_with(**request.query)
    except <CustomError> as e:
        response.status = e.msg.pop('status_code')
        return e.msg

    response.status = result.response.pop('status_code')

    return result.response


@route('/augment')
def augment():
    return error_else_response(<CustomClass>)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM