[英]try except not catching on function?
I am getting this valid error while preprocessing some data: 在预处理某些数据时出现此有效错误:
9:46:56.323 PM default_model Function execution took 6008 ms, finished with status: 'crash'
9:46:56.322 PM default_model Traceback (most recent call last):
File "/user_code/main.py", line 31, in default_model
train, endog, exog, _, _, rawDf = preprocess(ledger, apps)
File "/user_code/Wrangling.py", line 73, in preprocess
raise InsufficientTimespanError(args=(appDf, locDf))
That's occurring here: 这是在这里发生的:
async def default_model(request):
request_json = request.get_json()
if not request_json:
return '{"error": "empty body." }'
if 'transaction_id' in request_json:
transaction_id = request_json['transaction_id']
apps = [] # array of apps whose predictions we want, or uempty for all
if 'apps' in request_json:
apps = request_json['apps']
modelUrl = None
if 'files' in request_json:
try:
files = request_json['files']
modelUrl = getModelFromFiles(files)
except:
return package(transaction_id, error="no model to execute")
else:
return package(transaction_id, error="no model to execute")
if 'ledger' in request_json:
ledger = request_json['ledger']
try:
train, endog, exog, _, _, rawDf = preprocess(ledger, apps)
# ...
except InsufficientTimespanError as err:
return package(transaction_id, error=err.message, appDf=err.args[0], locDf=err.args[1])
And preprocess is correctly throwing my custom error: 并且预处理正确地引发了我的自定义错误:
def preprocess(ledger, apps=[]):
"""
convert ledger from the server, which comes in as an array of csv entries.
normalize/resample timeseries, returning dataframes
"""
appDf, locDf = splitLedger(ledger)
if len(appDf) < 3 or len(locDf) < 3:
raise InsufficientDataError(args=(appDf, locDf))
endog = appDf['app_id'].unique().tolist()
exog = locDf['location_id'].unique().tolist()
rawDf = normalize(appDf, locDf)
trainDf = cutoff(rawDf.copy(), apps)
rawDf = cutoff(rawDf.copy(), apps, trim=False)
# TODO - uncomment when on realish data
if len(trainDf) < 2 * WEEKS:
raise InsufficientTimespanError(args=(appDf, locDf))
The thing is, it is in a try``except
block precisely because I want to trap the error and return a payload with the error, rather than crashing with a 500 error. 事实是,它在
try``except
块中是因为我想捕获错误并返回带有错误的有效负载,而不是因500错误而崩溃。 But its crashing on my custom error, in the try block, anyway. 但是无论如何,它在try块中崩溃于我的自定义错误。 Right on that line calling
preprocess
. 就在那行调用
preprocess
。
This must be a failure on my part to conform to proper python code. 就我而言,这一定是一个失败,无法符合正确的python代码。 But I'm not sure what I am doing wrong.
但是我不确定自己在做什么错。 The environment is python 3.7
环境是python 3.7
Here's where that error is defined, in Wrangling.py: 这是在Wrangling.py中定义错误的地方:
class WranglingError(Exception):
"""Base class for other exceptions"""
pass
class InsufficientDataError(WranglingError):
"""insufficient data to make a prediction"""
def __init__(self, message='insufficient data to make a prediction', args=None):
super().__init__(message)
self.message = message
self.args = args
class InsufficientTimespanError(WranglingError):
"""insufficient timespan to make a prediction"""
def __init__(self, message='insufficient timespan to make a prediction', args=None):
super().__init__(message)
self.message = message
self.args = args
And here is how main.py declares (imports) it: 这是main.py声明(导入)它的方式:
from Wrangling import preprocess, InsufficientDataError, InsufficientTimespanError, DataNotNormal, InappropriateValueToPredict
Your preprocess
function is declared async
. 您的
preprocess
函数被声明为async
。 This means the code in it isn't actually run where you call preprocess
, but instead when it is eventually await
ed or passed to a main loop (like asyncio.run
). 这意味着其中的代码实际上不会在调用
preprocess
地方运行,而是在最终await
或传递给主循环(例如asyncio.run
)时运行。 Because the place where it is run is no-longer in the try block in default_model
, the exception is not caught. 因为在
default_model
的try块中不再运行它,所以不会捕获异常。
You could fix this in a few ways: 您可以通过以下几种方法解决此问题:
preprocess
not async preprocess
不同步 default_model
async too, and await
on preprocess
. default_model
异步,并await
preprocess
。 Do the line numbers in the error match up with the line numbers in your code? 错误中的行号是否与代码中的行号匹配? If not is it possible that you are seeing the error from a version of the code before you added the try...except?
如果不是,则在添加try ... except之前,您可能会从代码版本中看到错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.