Context . I have Flask routes defined for different API endpoints, and each endpoint calls a controller class with specific parameters (uid, project_id, etc.).
@app.route('/sample/route', methods=['POST']) @require_json_payload @require_fields({ 'pid', 'params' }) def route_handler(arg1, arg2):
The controller (proj_cntr) is responsible for determining, say, if a given PID is valid, if this user has the right to perform an action and another check of business logic.
I noticed that I c / paste a lot of code like this in different controllers:
if not project_object: sys_logger.info('...') raise ProjCntrException('PID %d does not exist' % pid)
Putting these checks in the decorators seems to be best done. But I'm not sure which error handling pattern is best practice if validation fails.
1) Should I create custom user exceptions (InvalidProjException, PermissionsException, etc.) for each decorator to raise?
Problems . The caller method lock will look bloated. Also, is it good to assume that the caller knows what exceptions decorators of the caller adorn?
2) The decorator passes an additional error argument to the method, and the method decides which exception to raise. Thus, the caller method knows what type of exception to expect and handle.
Problems : The approach seems a bit overworked and confusing.
Sorry for the detailed question. Any thoughts / ideas are welcome.
python flask exception error-handling
Albert e
source share