我有以下代码:
return requestAsync({
method: 'GET',
url: 'https://' + servers[num - 1] + ':8033/version.txt'
}).then().catch()
我尝试在当时的处理程序中抛出一个错误但是没有用
如果在then处理程序中没有满足条件,我想抛出catch处理程序处理的错误。我该怎么做呢?
代码:
var P = require('bluebird');
var defer = function () {
var resolve, reject;
var promise = new P(function () {
resolve = arguments[0];
reject = arguments[1];
});
return {
resolve: function () {
resolve.apply(null, arguments);
return promise;
},
reject: function () {
reject.apply(null, arguments);
return promise;
},
promise: promise
};
};
var pool = {maxSockets: Infinity};
var requestAsync = function (options) {
options.pool = pool;
options.timeout = 60000;
options.rejectUnauthorized = false;
options.strictSSL = false;
var deferred = defer();
var r = request(options, function (err, res, body) {
if (err) {
return deferred.reject(err);
}
deferred.resolve(res, body);
});
deferred.promise.req = r;
return deferred.promise;
};
return requestAsync({
method: 'GET',
url: 'https://' + servers[num - 1] + ':8033/version.txt'
}).then(function (response) {
throw new Error('Server is not taken');
}).catch(function (err) { });
答案 0 :(得分:4)
您可以手动throw
错误:
requestAsync({
method: 'GET',
url: 'https://' + servers[num - 1] + ':8033/version.txt'
})
.then(function () {
throw new Error("Catch me")
}))
.catch(function (error) {
console.error(error)
})
jsbin:https://jsbin.com/dewiqafaca/edit?html,js,console,output
答案 1 :(得分:0)
只需使用package threadpool;
import java.util.logging.Level;
import java.util.logging.Logger;
class ThreadPoolsThread
extends Thread {
private BlockingQueueCustom<Runnable> taskQueue;
private ThreadPool threadPool;
public ThreadPoolsThread(BlockingQueueCustom<Runnable> queue, ThreadPool threadPool) {
this.taskQueue = queue;
this.threadPool = threadPool;
}
public void run() {
for (;;) {
Runnable runnable = null;
while ((!this.threadPool.isPoolShutDownInitiated()) && (this.taskQueue.size() == 0)) {
}
if ((this.threadPool.isPoolShutDownInitiated()) && (this.taskQueue.size() == 0)) {
break;
}
try {
runnable = (Runnable) this.taskQueue.take();
} catch (InterruptedException ex) {
Logger.getLogger(ThreadPoolsThread.class.getName()).log(Level.SEVERE, null, ex);
break;
}
if (runnable == null) {
break;
}
runnable.run();
if ((this.threadPool.isPoolShutDownInitiated())
&& (this.taskQueue.size() == 0)) {
interrupt();
try {
Thread.sleep(1L);
} catch (InterruptedException ex) {
Logger.getLogger(ThreadPoolsThread.class.getName()).log(Level.SEVERE, null, ex);
break;
}
}
}
}
}
在throw
函数中生成标准JavaScript exception,它应该使用您提供的任何值作为参数调用catch块中的函数。