【发布时间】:2022-07-07 16:43:09
【问题描述】:
这是我对模型的一种方法:
return Attribute::make(
set: fn ($value) => CarbonInterval::fromString($value)->spec(),
);
但是,如果该值有些乱码,则会抛出 Carbon\Exceptions\InvalidIntervalException;
在此处捕获错误并保持属性不变的最佳方法是什么?
【问题讨论】:
这是我对模型的一种方法:
return Attribute::make(
set: fn ($value) => CarbonInterval::fromString($value)->spec(),
);
但是,如果该值有些乱码,则会抛出 Carbon\Exceptions\InvalidIntervalException;
在此处捕获错误并保持属性不变的最佳方法是什么?
【问题讨论】:
您可以在这里使用 php try-catch 作为:
// Try this
try {
return Attribute::make(
set: fn ($value) => CarbonInterval::fromString($value)->spec(),
);
}
//catch exception if trying fails
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
【讨论】: