简体   繁体   中英

How can I transfer exception text from php to javascript

I have a file download mechanism with axios and laravel. From the side of php I have several situations where I have to throw exceptions.

for example

    $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');
    }

In my controller I pass the data to the side js with json array

       if($resultUpload === true){

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

   }else{

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

   }

    return json_encode($json_array);

then in js I just use result.text . My question is in the following. Is it possible, in any way, to pass the text from exception to the side js?

As @J.Meijer mentioned, you can use try ... catch statement. so your code will be:

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

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

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

I didn't test this code so that this only give you an idea.

In Laravel this mechanism already exists

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM