大佬们,新人求助。关于控制器里面的try,catch 总是拦截 到HttpResponseException,应该怎么处理啊?
开发
后台

app/common/controller/Backend.php 中result 方法,抛出HttpResponseException,来做接口返回值。
我在业务代码中,使用try,catch总是拦截到它,应该怎么处理?

我的代码:

public function uploadImg(Request $request): void
    {
        if ($request->isPost()) {
            try {
                // 获取上传的文件
                $file = request()->file('file');
                if (empty($file)) {
                    throw new \Exception("文件上传失败");
                }
                $size = 3000 * 1024;
                $fSize = $file->getSize();
                if ($size < $fSize) {
                    throw new \Exception("文件超标了");
                }
                $type = $file->getMime();
                $allowed_types = array('image/png', 'image/jpg', 'image/jpeg');
                if (!in_array($type, $allowed_types)) {
                    throw new \Exception("请上传图片文件");
                }
                $filename = $file->getOriginalName(); // 假设文件名为example.txt
                // 获取文件名
                $original_name = pathinfo($filename, PATHINFO_FILENAME);
                // 获取文件扩展名
                $extension = pathinfo($filename, PATHINFO_EXTENSION);
                // 生成新文件名
                $new_filename = $original_name . '_' . dechex(time()) . '.' . $extension;
                // 保存文件 到public配置下的avatar目录下
                $saveName = \think\facade\Filesystem::disk("public")->putFileAs('wechat', $file, $new_filename);
                // 文件上传成功
                $this->success("done", $saveName);
            } catch (\Exception $e) {
                  // 在这里就拦截到HttpResponseException,然后就走了下面的error。
                Log::write("上传失败 > " . $e->getMessage(), 'comm_uploadImg');
                $this->error($e->getMessage());
            }
        } else {
            $this->error('301', 301);
        }
    }
5个回答默认排序 投票数排序
YANG001
YANG001
这家伙很懒,什么也没写~
6月前

别在try代码块里边执行success不就行了

cander0815
cander0815回复YANG001
这家伙很懒,什么也没写~
6月前

就是说要返回的数据在try外面创建一个变量? 根据这个变量有没有值来判断走成功还是失败? 感觉有点反人类啊

liuxiansen
liuxiansen回复cander0815
这家伙很懒,什么也没写~
3月前

确实, 我也觉得这个有点反人类, 让人不适的很.
为此, 我专门注册了个账号, 发了个帖子, 希望得到框架作者的回复.

有兴趣可以关注一下. https://ask.buildadmin.com/info/886

ﻩﻩ天天~zZ
ﻩﻩ天天~zZ
这家伙很懒,什么也没写~
6月前

catch (HttpResponseException $e)

lysong1991
lysong1991
这家伙很懒,什么也没写~
6月前

try代码 使用 throw 抛异常

dd0754
dd0754
这家伙很懒,什么也没写~
6月前
public function uploadImg(Request $request): void
{
    if (!$request::isPost()) {
        $this->error('301', 301);
    }
    try {
        // 业务代码
    } catch (\Exception $e) {
        $this->error($e->getMessage());
    }
    $this->success("done", []);
}
qiuxs
qiuxs
这家伙很懒,什么也没写~
6月前

官方用throw 抛出结果,用catch 刚好捕获。

请先登录
0
1
0
7