Задача: У меня есть несколько ссылок, которые мне нужно проверить, не сломаны ли.
Если они есть, я нарушаю процесс CI и уведомляю, что есть что исправить :)!
Как я это делаю:
- go через группу ссылок (итерацию) с проверкой для
- : отправка запроса HEAD для каждой ссылки и отлов ошибки
- в блоке catch попробуй сгенерировать ошибку
Проблема: при выдаче ошибки выдает ошибку о том, что она не перехватывается. Ниже я привожу пример
(node:20895) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block,
or by rejecting a promise which was not handled with .catch().
To terminate the node process on unhandled promise rejection,
use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:20895) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated.
In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Код:
const fs = require('fs')
const axios = require('axios')
const link_file = fs.readFileSync('links.json');
const links = JSON.parse(link_file)
var unique_links = [...new Set(links)]
class urlChecker{
constructor(){
this.blacklist = [
'localhost',
'DOCKER_MACHINE_IP',
'APP_NAME',
'PACKAGE_NAME',
'LOAD_BALANCER',
'YOUR_AWS_ACCOUNT_ID',
'YOUR_IP',
'YOUR_MACHINE_IP',
'EXTERNAL_IP',
'127.0.0.1',
'localhost',
'data:',
'geo:',
'javascript:',
'mailto:',
'sms:',
'tel:'
];
this.excluded_specific_cases = {
'https://signup.heroku.com': 500,
'https://news.ycombinator.com': 405
};
this.error_list = [];
this.total_cases = 0;
}
async checkIsItLast(){
if (this.total_cases === 0){
console.log(`It's a last case - Urra`)
let msg = this.error_list.join('\n');
return new Promise(function (resolve, reject) {
reject(Error(msg))
})
}
}
in_whitelist(link){
let in_list = true;
if (link.indexOf('http') === -1){ in_list = false; }
this.blacklist.map((keyword) => {
if (link.indexOf(keyword) >= 0){ in_list = false; }
});
return in_list;
}
in_specific_case(link, statusCode){
let is_true = false;
Object.keys(this.excluded_specific_cases).map((keyword) => {
let keyword_in = link.indexOf(keyword);
if (keyword_in >= 0){
is_true = this.excluded_specific_cases[keyword] === statusCode;
}
});
return is_true;
}
check(link) {
let self = this;
if(this.in_whitelist(link)){
self.total_cases += 1;
axios.head(link)
.then(function(){
self.total_cases -= 1;
})
.catch((err) => {
self.total_cases -= 1;
this.error(err);
})
.then(function(){
self.checkIsItLast();
})
}
}
returnsPromise(msg) {
return
}
error(error){
let response = error.response || {};
let statusCode = response.status || null,
url = error.config.url;
if (statusCode && statusCode > 0){
if (this.in_specific_case(url, statusCode) === false && statusCode >= 400){
let msg = `The link: ${url} is broken, statusCode: ${statusCode}`;
this.error_list.push(msg);
}
}
else{
let msg = `The link: ${url} is broken, code: ${error.code}`;
this.error_list.push(msg);
}
}
}
const checker = new urlChecker();
unique_links.map((link) => {
checker.check(link);
});
Но, интересная вещь вне топора ios это работает отлично !
Примечание: мне нужно просто выдать ошибку без перехвата, чтобы прервать процесс сборки!
Малый часть кода не путать:
check(link) {
if(this.in_whitelist(link)){
axios.head(link)
.catch((err) => {
throw new Error(`The link ${link} is broken`);
})
}
}