Using PHP code to implement error handling and exception capture of Baidu Wenxin Yiyan API interface

WBOY
Release: 2023-08-26 18:14:01
Original
1262 people have browsed it

Using PHP code to implement error handling and exception capture of Baidu Wenxin Yiyan API interface

Use PHP code to implement error handling and exception capture of Baidu Wenxin Yiyan API interface

Baidu Wenxin Yiyan API is a very popular phrase generation interface , which can return a random sentence, providing us with many interesting phrases and famous quotes. However, when we use this interface, we may sometimes encounter some problems, such as request timeout, error information returned, etc. In order to improve the user experience, we need to add error handling and exception catching functions to the code to increase the robustness and reliability of the program.

First, we need to use the cURL function to send a request and get the return value of the interface. In order to facilitate subsequent error handling and exception capture, we encapsulate this process into a function:

function getOneWord() {
    $url = 'https://v1.alapi.cn/api/word';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpCode == 200) {
        $result = json_decode($result, true);
        if ($result['code'] == 200) {
            return $result['data']['content'];
        } else {
            throw new Exception($result['msg']);
        }
    } else {
        throw new Exception('Request failed: ' . $httpCode);
    }
}
Copy after login

In the above code, we use the cURL function to send a GET request and set the timeout to 5 seconds. If the request is successful (return code is 200), then we parse the returned JSON data into an associative array to determine whether the code is 200. If so, return the content field as a phrase; otherwise, throw a custom exception, exception The information is the error information returned by the interface.

In our business code, we can use the try-catch statement to capture this exception and perform corresponding error handling:

try {
    $oneWord = getOneWord();
    echo '今日一句:' . $oneWord;
} catch (Exception $e) {
    echo '获取短语失败:' . $e->getMessage();
}
Copy after login

In the above code, we call the getOneWord function to obtain a sentence Phrase, if the acquisition is successful, it will be output to the page; if the acquisition fails, an error message will be output.

In addition to catching exceptions thrown by the Exception class, we can also customize some exception classes to handle different errors differently. For example, we can define a TimeoutException class to handle the request timeout:

class TimeoutException extends Exception {
    public function __toString() {
        return '请求超时,请稍后重试。';
    }
}

function getOneWord() {
    // ...
    if ($httpCode == 200) {
        // ...
    } else if ($httpCode == 28) {
        throw new TimeoutException();
    } else {
        throw new Exception('Request failed: ' . $httpCode);
    }
}
Copy after login

In the above code, we define a TimeoutException class, inherit from the Exception class, and override the __toString method, using to return a custom error message. In the getOneWord function, this exception is thrown when the request times out, and then the exception is captured in the business code and processed accordingly.

Through the above error handling and exception catching functions, we can better deal with some unforeseen situations and improve the stability and reliability of the program. In actual development, we can refine the error handling and exception capturing logic according to specific needs, and provide more friendly error information and recovery mechanisms to provide a better user experience.

The above is the detailed content of Using PHP code to implement error handling and exception capture of Baidu Wenxin Yiyan API interface. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!