自定义示例
- 1.打开
app/Exceptions
目录
定义一个类例如ApiException 专门用于返回api错误
<?php
## 继承Exception类
namespace App\Exceptions;
use Exception;
class ApiException extends Exception
{
/*
* author yaoLiuYang
* date:2021/4/16
*/
public function __construct($message = "")
{
$this->message = $message;
parent::__construct($message);
}
}
- 2.使用示例
try {
$params = $request->only('id');
$club = Club::find($params['id']);
if ($club == null) {
#抛出异常
throw new ApiException('社团不存在');
}
$club->club_images = $club->clubGallery()->take(3)->pluck('img_url');
return $this->success($club);
} catch (ApiException $exception) {
#这里自动捕获异常
return $this->error($exception->getMessage());
}