【问题标题】:Laravel attribute set catch exceptionLaravel 属性集捕获异常
【发布时间】:2022-07-07 16:43:09
【问题描述】:

这是我对模型的一种方法:

return Attribute::make(
    set: fn ($value) => CarbonInterval::fromString($value)->spec(),
);

但是,如果该值有些乱码,则会抛出 Carbon\Exceptions\InvalidIntervalException;

在此处捕获错误并保持属性不变的最佳方法是什么?

【问题讨论】:

    标签: laravel laravel-9


    【解决方案1】:

    您可以在这里使用 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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-22
      • 2014-12-25
      • 2017-09-11
      相关资源
      最近更新 更多