Decorate a function to automatically convert its return type to a string
    using a custom function.

    Web-based service functions must return text to the client.  Tangelo
    contains default logic to convert many kinds of values into string, but this
    decorator allows the service writer to specify custom behavior falling
    outside of the default.  If the conversion fails, an appropriate server
    error will be raised.

def return_type(rettype):
    """
    Decorate a function to automatically convert its return type to a string
    using a custom function.

    Web-based service functions must return text to the client.  Tangelo
    contains default logic to convert many kinds of values into string, but this
    decorator allows the service writer to specify custom behavior falling
    outside of the default.  If the conversion fails, an appropriate server
    error will be raised.
    """
    def wrap(f):
        @functools.wraps(f)
        def converter(*pargs, **kwargs):
            # Run the function to capture the output.
            result = f(*pargs, **kwargs)

            # Convert the result using the return type function.
            try:
                result = rettype(result)
            except ValueError as e:
                http_status(500, "Return Value Conversion Failed")
                content_type("application/json")
                return {"error": str(e)}
            return result

        return converter
    return wrap