如何将异常文本从php传输到javascript

问题描述 投票:0回答:2

我有一个带有axios和laravel的文件下载机制。从php的一面我有几种情况我必须抛出异常。

例如

    $result = file_put_contents($filepath, $filedata);

    if($result){

        $photoModer = new PhotoModeration();
        $photoModer->newUserUpload($filepath);


        return true;
    }else{
        throw new Exceptions\FileUploadException('Can not upload file');
    }

在我的控制器中,我使用json数组将数据传递给js

       if($resultUpload === true){

       $json_array = [
           'status' => 'success',
           'message' => 'Success'
       ];

   }else{

       $json_array = [
           'status' => 'error',
           'message' => 'Error'
       ];

   }

    return json_encode($json_array);

然后在js我只使用result.text。我的问题如下。是否有可能将文本从异常传递给js?

javascript php vuejs2 axios laravel-5.5
2个回答
0
投票

正如@ J.Meijer所提到的,你可以使用try ... catch声明。所以你的代码将是:

try (file_put_contents($filepath, $filedata)){

    $photoModer = new PhotoModeration();
    $photoModer->newUserUpload($filepath);

    return true;
} catch (Exception $e) {
    return json_encode($e);
}

我没有测试这段代码,所以这只会给你一个想法。


0
投票

在Laravel中,这种机制已经存在

https://laravel.com/docs/5.5/errors#render-method

© www.soinside.com 2019 - 2024. All rights reserved.