Commit 151292b5 authored by Samuel GAIST's avatar Samuel GAIST
Browse files

[decorators] Add raise_on_error decorator

Click turns functions into "commands" which has the following consequences:
- Any return statement means that it has succeeded whatever the value returned
  therefore the exit code will be 0
- To "fail" properly an exception must be raised which will return an exit
  code of 1
- Other exceptions will be treated as usage error and have an exit code
  of 2

The raise_on_error decorator will take the returned value of the wrapped
function and raise a generic error with the exit code set to what the
function has returned.
parent eb1e771e
# vim: set fileencoding=utf-8 :
###############################################################################
# #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/ #
# Contact: beat.support@idiap.ch #
# #
# This file is part of the beat.cmdline module of the BEAT platform. #
# #
# Commercial License Usage #
# Licensees holding valid commercial BEAT licenses may use this file in #
# accordance with the terms contained in a written agreement between you #
# and Idiap. For further information contact tto@idiap.ch #
# #
# Alternatively, this file may be used under the terms of the GNU Affero #
# Public License version 3 as published by the Free Software and appearing #
# in the file LICENSE.AGPL included in the packaging of this file. #
# The BEAT platform is distributed in the hope that it will be useful, but #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY #
# or FITNESS FOR A PARTICULAR PURPOSE. #
# #
# You should have received a copy of the GNU Affero Public License along #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/. #
# #
###############################################################################
from functools import wraps
import click
def raise_on_error(view_func):
"""Raise a click exception if returned value is not zero.
Click exits successfully if anything is returned, in order to exit properly
when something went wrong an exception must be raised.
"""
def _decorator(*args, **kwargs):
value = view_func(*args, **kwargs)
if value not in [None, 0]:
exception = click.ClickException("Error occured")
exception.exit_code = value
raise exception
return value
return wraps(view_func)(_decorator)
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment